How to set up Google Analytics through Google Tag Manager for Next-Js?

后端 未结 6 982
北恋
北恋 2021-02-13 16:24

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         


        
6条回答
  •  灰色年华
    2021-02-13 16:44

    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)
    

提交回复
热议问题