Google Analytics Module for Nuxt.js applications providing Universal Analytics integration
npx @tessl/cli install tessl/npm-nuxtjs--google-analytics@2.4.00
# @nuxtjs/google-analytics
1
2
@nuxtjs/google-analytics is a Nuxt.js module that integrates Google Analytics (GA3/Universal Analytics) into Nuxt 2 applications using the vue-analytics library. It provides automatic page tracking, event tracking, and comprehensive analytics features through a simple configuration interface.
3
4
**⚠️ Important**: This module only supports GA3/Universal Analytics and is not compatible with GA4. For Nuxt 3 applications, use `nuxt-gtag` instead.
5
6
## Package Information
7
8
- **Package Name**: @nuxtjs/google-analytics
9
- **Package Type**: npm
10
- **Language**: JavaScript/TypeScript
11
- **Installation**: `npm install @nuxtjs/google-analytics`
12
- **Nuxt Version**: Nuxt 2.x only
13
14
## Core Imports
15
16
This module is registered as a Nuxt module, not imported directly:
17
18
```javascript
19
// nuxt.config.js
20
export default {
21
buildModules: [
22
'@nuxtjs/google-analytics' // Nuxt 2.9+
23
],
24
// OR for older versions:
25
modules: [
26
'@nuxtjs/google-analytics'
27
]
28
}
29
```
30
31
## Basic Usage
32
33
```javascript
34
// nuxt.config.js
35
export default {
36
buildModules: [
37
'@nuxtjs/google-analytics'
38
],
39
googleAnalytics: {
40
id: 'UA-12301-2' // Your Google Analytics tracking ID
41
}
42
}
43
```
44
45
Access the analytics instance in your components:
46
47
```javascript
48
export default {
49
mounted() {
50
// Track an event
51
this.$ga.event('button', 'click', 'nav buttons', 1)
52
53
// Track a page view
54
this.$ga.page('/my-page')
55
}
56
}
57
```
58
59
## Architecture
60
61
@nuxtjs/google-analytics is built around a simple yet effective modular architecture:
62
63
- **Module Layer** (`module.js`): Nuxt module that processes configuration options, handles development mode behavior, and registers the client-side plugin. Merges module options with runtime config and ensures backward compatibility.
64
65
- **Plugin Layer** (`plugin.js`): Client-side plugin that initializes vue-analytics with the router instance and injects the `$ga` instance into the Nuxt context. Handles async ID resolution and runtime configuration merging.
66
67
- **Integration Layer**: TypeScript definitions that augment Nuxt's context, Vue instances, and Vuex store with the `$ga` property, providing type safety across the application.
68
69
- **Analytics Engine**: The underlying vue-analytics library that provides the actual Google Analytics functionality, including automatic page tracking, event batching, and comprehensive GA feature support.
70
71
The data flow follows this pattern:
72
1. Module processes configuration during build
73
2. Plugin initializes vue-analytics on client-side with processed options
74
3. `$ga` instance becomes available throughout the application
75
4. Analytics data flows through vue-analytics to Google Analytics
76
77
## Capabilities
78
79
### Module Registration
80
81
The main Nuxt module function that configures and registers the Google Analytics plugin.
82
83
```javascript { .api }
84
/**
85
* Main module function - automatically called by Nuxt
86
* @param moduleOptions - Module configuration options
87
*/
88
function analyticsModule(moduleOptions: ModuleOptions): void;
89
```
90
91
### Module Configuration
92
93
Configuration options for the Google Analytics module.
94
95
```typescript { .api }
96
interface ModuleOptions {
97
/** Google Analytics tracking ID (required) */
98
id: string;
99
/** Async function that returns the tracking ID */
100
asyncID?: (context: Context) => Promise<string>;
101
/** Enable module in development mode (default: true) */
102
dev?: boolean;
103
/** Debug configuration */
104
debug?: {
105
/** Enable debug mode */
106
enabled?: boolean;
107
/** Send hits to GA (default: undefined in dev mode, true in production) */
108
sendHitTask?: boolean;
109
};
110
/** Detect duplicate analytics scripts */
111
checkDuplicatedScript?: boolean;
112
/** Disable automatic script loading */
113
disableScriptLoader?: boolean;
114
/** Legacy alias for id (deprecated) */
115
ua?: string;
116
/** All vue-analytics options are also supported */
117
[key: string]: any;
118
}
119
```
120
121
### Runtime Context Injection
122
123
The module injects the `$ga` instance into the Nuxt context, making it available throughout your application.
124
125
```typescript { .api }
126
interface NuxtContext {
127
/** Vue Analytics instance for tracking */
128
$ga: VueAnalytics;
129
}
130
131
interface Vue {
132
/** Vue Analytics instance for tracking */
133
$ga: VueAnalytics;
134
}
135
136
interface Store<S> {
137
/** Vue Analytics instance for tracking in Vuex store */
138
$ga: VueAnalytics;
139
}
140
```
141
142
### Plugin Functionality
143
144
The client-side plugin that initializes vue-analytics and provides the tracking functionality.
145
146
```javascript { .api }
147
/**
148
* Plugin function that sets up Vue Analytics
149
* Automatically called by Nuxt on client-side
150
*/
151
async function plugin(context: Context, inject: Function): Promise<void>;
152
```
153
154
### Configuration Methods
155
156
Multiple ways to configure the module:
157
158
```javascript { .api }
159
// In nuxt.config.js
160
export default {
161
googleAnalytics: {
162
id: 'UA-XXX-X'
163
},
164
165
// Runtime configuration support
166
publicRuntimeConfig: {
167
googleAnalytics: {
168
id: process.env.GA_ID
169
}
170
}
171
}
172
```
173
174
### Async ID Resolution
175
176
Support for dynamically resolving the tracking ID at runtime:
177
178
```typescript { .api }
179
interface AsyncIDFunction {
180
(context: Context): Promise<string>;
181
}
182
183
// Usage example:
184
const config = {
185
googleAnalytics: {
186
asyncID: async (context) => {
187
// Resolve ID based on context
188
return context.route.params.siteId
189
? `UA-${context.route.params.siteId}-1`
190
: 'UA-DEFAULT-1';
191
}
192
}
193
}
194
```
195
196
## Types
197
198
### Nuxt Context Augmentation
199
200
```typescript { .api }
201
declare module '@nuxt/vue-app' {
202
interface Context {
203
$ga: VueAnalytics;
204
}
205
interface NuxtAppOptions {
206
$ga: VueAnalytics;
207
}
208
}
209
210
declare module '@nuxt/types' {
211
interface Context {
212
$ga: VueAnalytics;
213
}
214
interface NuxtAppOptions {
215
$ga: VueAnalytics;
216
}
217
interface Configuration {
218
googleAnalytics?: InstallOptions;
219
}
220
}
221
222
declare module 'vue/types/vue' {
223
interface Vue {
224
$ga: VueAnalytics;
225
}
226
}
227
228
declare module 'vuex' {
229
interface Store<S> {
230
$ga: VueAnalytics;
231
}
232
}
233
```
234
235
### VueAnalytics Type
236
237
The `$ga` instance provides the full vue-analytics API with comprehensive Google Analytics functionality:
238
239
```typescript { .api }
240
interface VueAnalytics {
241
/** Track a page view with flexible parameter support */
242
page(path: string | object): void;
243
page(route: Route): void;
244
page(path: string, title: string, location?: string): void;
245
246
/** Track an event with flexible parameters */
247
event(category: string, action: string, label?: string, value?: number): void;
248
event(eventObject: {
249
eventCategory: string;
250
eventAction: string;
251
eventLabel?: string;
252
eventValue?: number;
253
[key: string]: any;
254
}): void;
255
256
/** Track screen views for mobile/SPA applications */
257
screenview(screenName: string): void;
258
screenview(screenObject: {
259
screenName: string;
260
appName?: string;
261
appVersion?: string;
262
[key: string]: any;
263
}): void;
264
265
/** Track user timing for performance metrics */
266
time(category: string, variable: string, value: number, label?: string): void;
267
time(timingObject: {
268
timingCategory: string;
269
timingVar: string;
270
timingValue: number;
271
timingLabel?: string;
272
[key: string]: any;
273
}): void;
274
275
/** Track social interactions */
276
social(network: string, action: string, target: string): void;
277
social(socialObject: {
278
socialNetwork: string;
279
socialAction: string;
280
socialTarget: string;
281
[key: string]: any;
282
}): void;
283
284
/** Track exceptions and errors */
285
exception(description: string, fatal?: boolean): void;
286
exception(exceptionObject: {
287
exDescription: string;
288
exFatal?: boolean;
289
[key: string]: any;
290
}): void;
291
292
/** Set custom dimensions, metrics, and configuration */
293
set(field: string, value: any): void;
294
set(fieldsObject: { [field: string]: any }): void;
295
296
/** Require and configure GA plugins */
297
require(pluginName: string, pluginOptions?: object): void;
298
299
/** Send custom hit to Google Analytics */
300
send(hitType: string, params: object): void;
301
302
/** Core query method for direct GA commands */
303
query(...args: any[]): void;
304
305
/** Enhanced e-commerce tracking */
306
ecommerce: {
307
/** Add e-commerce item (classic e-commerce) */
308
addItem(itemData: {
309
id: string;
310
name?: string;
311
category?: string;
312
sku?: string;
313
price?: number;
314
quantity?: number;
315
}): void;
316
317
/** Add e-commerce transaction (classic e-commerce) */
318
addTransaction(transactionData: {
319
id: string;
320
affiliation?: string;
321
revenue?: number;
322
shipping?: number;
323
tax?: number;
324
}): void;
325
326
/** Add enhanced e-commerce product */
327
addProduct(productData: {
328
id: string;
329
name?: string;
330
category?: string;
331
brand?: string;
332
variant?: string;
333
price?: number;
334
quantity?: number;
335
coupon?: string;
336
position?: number;
337
}): void;
338
339
/** Add product impression for enhanced e-commerce */
340
addImpression(impressionData: {
341
id: string;
342
name?: string;
343
category?: string;
344
brand?: string;
345
variant?: string;
346
list?: string;
347
position?: number;
348
price?: number;
349
}): void;
350
351
/** Set e-commerce action for enhanced e-commerce */
352
setAction(action: string, actionData?: {
353
id?: string;
354
affiliation?: string;
355
revenue?: number;
356
tax?: number;
357
shipping?: number;
358
coupon?: string;
359
list?: string;
360
step?: number;
361
option?: string;
362
}): void;
363
364
/** Add promotional data for enhanced e-commerce */
365
addPromo(promoData: {
366
id: string;
367
name?: string;
368
creative?: string;
369
position?: string;
370
}): void;
371
372
/** Send e-commerce data to Google Analytics */
373
send(): void;
374
375
/** Clear e-commerce data */
376
clear(): void;
377
};
378
}
379
```
380
381
## Usage Examples
382
383
### Event Tracking
384
385
```javascript
386
// Basic event tracking
387
this.$ga.event('button', 'click', 'navbar', 1)
388
389
// Object-based event tracking
390
this.$ga.event({
391
eventCategory: 'user',
392
eventAction: 'login',
393
eventLabel: 'social-media',
394
customDimension1: 'facebook'
395
})
396
```
397
398
### Page Tracking
399
400
```javascript
401
// Simple path tracking
402
this.$ga.page('/about')
403
404
// Router-based tracking (automatic)
405
this.$ga.page(this.$route)
406
407
// Custom page with title
408
this.$ga.page('/products', 'Product Catalog')
409
410
// Object-based page tracking
411
this.$ga.page({
412
page: '/special-page',
413
title: 'Special Page Title',
414
location: 'https://example.com/special-page'
415
})
416
```
417
418
### E-commerce Tracking
419
420
```javascript
421
// Add product to cart
422
this.$ga.ecommerce.addProduct({
423
id: 'SKU123',
424
name: 'Product Name',
425
category: 'Category',
426
brand: 'Brand',
427
variant: 'Color',
428
price: 15.99,
429
quantity: 1
430
})
431
432
// Purchase action
433
this.$ga.ecommerce.setAction('purchase', {
434
id: 'T12345',
435
affiliation: 'Online Store',
436
revenue: 35.43,
437
tax: 4.90,
438
shipping: 5.99,
439
coupon: 'SUMMER2023'
440
})
441
442
// Send e-commerce data
443
this.$ga.ecommerce.send()
444
```
445
446
### Custom Dimensions and Metrics
447
448
```javascript
449
// Set user properties
450
this.$ga.set('userId', 'user123')
451
this.$ga.set('customDimension1', 'premium-user')
452
453
// Bulk configuration
454
this.$ga.set({
455
userId: 'user123',
456
customDimension1: 'premium-user',
457
customDimension2: 'mobile-app',
458
customMetric1: 42
459
})
460
```
461
462
### Performance Timing
463
464
```javascript
465
// Track loading time
466
this.$ga.time('page', 'load', 3400, 'home-page')
467
468
// Object-based timing
469
this.$ga.time({
470
timingCategory: 'api',
471
timingVar: 'response',
472
timingValue: 245,
473
timingLabel: 'user-data'
474
})
475
```
476
477
### Exception Tracking
478
479
```javascript
480
// Track non-fatal exception
481
this.$ga.exception('API timeout', false)
482
483
// Track fatal exception
484
this.$ga.exception({
485
exDescription: 'Database connection failed',
486
exFatal: true,
487
customDimension3: 'production'
488
})
489
```
490
491
### Screen View Tracking
492
493
```javascript
494
// Mobile/SPA screen tracking
495
this.$ga.screenview('Home Screen')
496
497
// Detailed screen view
498
this.$ga.screenview({
499
screenName: 'Product Detail',
500
appName: 'MyApp',
501
appVersion: '1.2.0'
502
})
503
```
504
505
### Social Interaction Tracking
506
507
```javascript
508
// Track social shares
509
this.$ga.social('facebook', 'share', '/article/123')
510
511
// Object-based social tracking
512
this.$ga.social({
513
socialNetwork: 'twitter',
514
socialAction: 'tweet',
515
socialTarget: '/blog/analytics-guide'
516
})
517
```
518
519
### Advanced Configuration
520
521
```javascript
522
// Load enhanced e-commerce plugin
523
this.$ga.require('ec')
524
525
// Load display features
526
this.$ga.require('displayfeatures')
527
528
// Custom hit
529
this.$ga.send('event', {
530
eventCategory: 'custom',
531
eventAction: 'api-call',
532
nonInteraction: true
533
})
534
```
535
536
## Features
537
538
The module provides access to all vue-analytics features:
539
540
- **Automatic page tracking**: Tracks route changes automatically
541
- **Event batching**: Groups events for efficient sending
542
- **User timings**: Performance measurement tracking
543
- **Screen view tracking**: For mobile app analytics
544
- **Multiple domain ID support**: Track across multiple domains
545
- **E-commerce support**: Enhanced e-commerce tracking
546
- **Custom dimensions and metrics**: Extended tracking capabilities
547
- **Campaign tracking**: UTM parameter tracking
548
- **Social interaction tracking**: Social media engagement tracking
549
550
## Advanced Features
551
552
### Vuex Integration
553
554
The module automatically injects `$ga` into the Vuex store, enabling analytics tracking from actions and mutations:
555
556
```javascript
557
// In store actions
558
export const actions = {
559
async login({ commit }, userData) {
560
// Track login attempt
561
this.$ga.event('user', 'login-attempt', userData.provider)
562
563
try {
564
const result = await this.$axios.post('/auth/login', userData)
565
commit('SET_USER', result.data)
566
567
// Track successful login
568
this.$ga.event('user', 'login-success', userData.provider)
569
this.$ga.set('userId', result.data.id)
570
571
} catch (error) {
572
// Track login failure
573
this.$ga.exception('Login failed: ' + error.message, false)
574
}
575
}
576
}
577
```
578
579
### Multi-Tracker Support
580
581
Support for multiple Google Analytics properties:
582
583
```javascript
584
// nuxt.config.js
585
export default {
586
googleAnalytics: {
587
id: ['UA-XXXXX-1', 'UA-XXXXX-2'], // Multiple tracking IDs
588
// Configure trackers separately if needed
589
trackers: {
590
'UA-XXXXX-1': { name: 'primary' },
591
'UA-XXXXX-2': { name: 'secondary', debug: true }
592
}
593
}
594
}
595
```
596
597
### Custom Plugins and Features
598
599
Load additional Google Analytics plugins:
600
601
```javascript
602
// In a component or plugin
603
mounted() {
604
// Load enhanced e-commerce
605
this.$ga.require('ec')
606
607
// Load display features for demographics
608
this.$ga.require('displayfeatures')
609
610
// Load enhanced link attribution
611
this.$ga.require('linkid')
612
613
// Custom plugin with configuration
614
this.$ga.require('customPlugin', {
615
customParam: 'value'
616
})
617
}
618
```
619
620
### Cross-Domain Tracking
621
622
Configure cross-domain tracking for multiple domains:
623
624
```javascript
625
// nuxt.config.js
626
export default {
627
googleAnalytics: {
628
id: 'UA-XXXXX-1',
629
crossDomain: {
630
domains: ['example.com', 'shop.example.com'],
631
allowLinker: true
632
}
633
}
634
}
635
```
636
637
### Async ID Resolution
638
639
Dynamically resolve tracking IDs based on runtime context:
640
641
```javascript
642
// nuxt.config.js
643
export default {
644
googleAnalytics: {
645
asyncID: async (context) => {
646
// Get ID from API or based on route
647
if (context.route.params.tenant) {
648
const config = await context.$axios.$get(`/config/${context.route.params.tenant}`)
649
return config.gaTrackingId
650
}
651
return process.env.DEFAULT_GA_ID
652
}
653
}
654
}
655
```
656
657
### Content Groups and Custom Dimensions
658
659
Set up content grouping and custom dimensions:
660
661
```javascript
662
// In layouts or pages
663
mounted() {
664
// Set content group
665
this.$ga.set('contentGroup1', 'Blog Posts')
666
this.$ga.set('contentGroup2', 'Technology')
667
668
// Set custom dimensions
669
this.$ga.set('customDimension1', 'logged-in-user')
670
this.$ga.set('customDimension2', this.$auth.user?.subscription_type)
671
672
// Track page with content grouping
673
this.$ga.page(this.$route.path)
674
}
675
```
676
677
### Enhanced E-commerce Workflows
678
679
Complete e-commerce tracking implementation:
680
681
```javascript
682
// Product list view
683
methods: {
684
trackProductListView() {
685
this.products.forEach((product, index) => {
686
this.$ga.ecommerce.addImpression({
687
id: product.sku,
688
name: product.name,
689
category: product.category,
690
brand: product.brand,
691
list: 'Search Results',
692
position: index + 1
693
})
694
})
695
this.$ga.ecommerce.send()
696
},
697
698
trackProductClick(product, position) {
699
this.$ga.ecommerce.addProduct({
700
id: product.sku,
701
name: product.name,
702
category: product.category,
703
position: position
704
})
705
this.$ga.ecommerce.setAction('click', { list: 'Search Results' })
706
this.$ga.ecommerce.send()
707
}
708
}
709
```
710
711
### Performance Monitoring
712
713
Track application performance metrics:
714
715
```javascript
716
// In plugins or middleware
717
export default function({ $ga, route }) {
718
// Track page load timing
719
window.addEventListener('load', () => {
720
const navigation = performance.getEntriesByType('navigation')[0]
721
$ga.time('page', 'load', Math.round(navigation.loadEventEnd), route.path)
722
})
723
724
// Track API response times
725
const originalFetch = window.fetch
726
window.fetch = async (...args) => {
727
const start = performance.now()
728
try {
729
const response = await originalFetch(...args)
730
const duration = Math.round(performance.now() - start)
731
$ga.time('api', 'response', duration, args[0])
732
return response
733
} catch (error) {
734
$ga.exception(`API Error: ${args[0]}`, false)
735
throw error
736
}
737
}
738
}
739
```
740
741
## Development Mode
742
743
In development mode (when `this.options.dev` is true):
744
- Module is disabled unless `dev: true` is explicitly set in module options
745
- Hit sending is automatically disabled (`debug.sendHitTask` set to `false` if undefined)
746
- Debug information is available in browser console
747
748
## Legacy Support
749
750
- Converts deprecated `ua` option to `id` automatically
751
- Supports both `googleAnalytics` and `google-analytics` configuration keys
752
- Compatible with both Nuxt module registration methods
753
754
## Error Handling
755
756
The module gracefully handles:
757
- Missing tracking ID (module will not initialize)
758
- Network failures (hits are queued and retried)
759
- Duplicate script loading (with `checkDuplicatedScript` option)
760
761
## Migration Notes
762
763
- **From Nuxt 2 to Nuxt 3**: Use `nuxt-gtag` instead
764
- **To GA4**: This module does not support GA4, use dedicated GA4 solutions
765
- **Legacy `ua` option**: Automatically converted to `id`, but prefer using `id` directly
766
767
## References
768
769
This module provides access to the complete vue-analytics API. For comprehensive documentation of all analytics methods and advanced configuration options, see:
770
771
- **[vue-analytics Documentation](https://github.com/MatteoGabriele/vue-analytics)**: Complete API reference and advanced usage patterns
772
- **[Google Analytics Documentation](https://developers.google.com/analytics/devguides/collection/analyticsjs)**: Official Google Analytics documentation
773
- **[Enhanced E-commerce Guide](https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce)**: Detailed e-commerce tracking implementation
774
775
**Note**: vue-analytics is no longer actively maintained. For new projects, consider migrating to vue-gtag or nuxt-gtag for better long-term support.