In case this can help, I created this simple boilerplate for Nuxt 2 and GA4/GTAG for our POC.
import { GrowthBook } from '@growthbook/growthbook'
export default ({ env }, inject) => {
let growthBook = null
/**
* For initializing Growthbook
* @returns (null/Growthbook) Returns GrowthBook or null
*/
const initGrowthBook = async function () {
/* Prevent reinitializing Growthbook */
if (growthBook) {
return growthBook
}
/* Initialize Growthbook */
growthBook = new GrowthBook({
apiHost: env.GROWTHBOOK_API_HOST,
clientKey: env.GROWTHBOOK_API_KEY,
enableDevMode: env.NODE_ENV === 'development',
trackingCallback: (experiment, result) => {
// track using GA4
if ("gtag" in window) {
this.$gtag.query("event", "experiment_viewed", {
event_category: "experiment",
experiment_id: experiment.key,
variation_id: result.variationId,
})
} else {
console.warn("no gtag")
}
}
})
//Set user attributes
await this.$gtag.query('get', env.GA4_TRACKING_ID, 'client_id', (client_id)=>{
growthBook.setAttributes({
country: 'france',
id: client_id,
})
})
/* Load Growthbook features */
try {
await growthBook.loadFeatures({
autoRefresh: true,
timeout: 2000,
})
return growthBook
} catch (error) {
console.error('Failed to load features from GrowthBook', error)
return null
}
}
inject('initGrowthBook', initGrowthBook)