formerly I was using react-ga npm module to insert google analytics in my next js app. and It was simply like this:
import ReactGA from \'react-ga\'
export cons
I'm using redux in my next.js application.
And this is pretty good solution if you're using redux: redux-beacon + react-gtm-module.
here is initialization code. This code can be triggered with hooks or componentDidMount in _app.js or with redux action if you're using redux.
const dataLayer = { ...your dataLayer config... }
const tagManagerArgs = {
gtmId: process.env.GTM_ID,
auth: process.env.GTM_AUTH,
preview: process.env.GTM_PREVIEW,
dataLayer
}
TagManager.initialize(tagManagerArgs)
below is middleware created with eventMap.
import { EventsMapper, createMiddleware } from 'redux-beacon'
import GoogleTagManager from '@redux-beacon/google-tag-manager'
const gtm = GoogleTagManager()
export const eventsMap: EventsMapper = action => {
switch (action.type) {
default:
return []
}
}
export const gtmMiddleware = createMiddleware(eventsMap, gtm)