Home > other >  Is it possible to set the Analytics ID in gatsby-node.js?
Is it possible to set the Analytics ID in gatsby-node.js?

Time:11-11

I'm using Gatsby to create a static page. The contents are comming from a CMS with rest-API.

Now I would like to add Google-Analyitcs, and also save the trackingId in the CMS. But when I'm using the gatsby-plugin-google-analytics, I have to set the trackingId in the gatsby-config.js.

Is there any way, to fetch the data in gatsby-node.js and then set/change the trackingId for the plugin?

I am grateful for any help.

CodePudding user response:

No, you can't.

In the end, gatsby-plugin-google-analytics or any similar plugin what it's doing is to customize the html.js to add a script with the ID in it. This is created as a boilerplate/template for the content coming from your data sources (in your gatsby-node.js) while your site is being built, as you can see in the docs:

Gatsby gives plugins and site builders many APIs for building your site. Code in the file gatsby-node.js is run once in the process of building your site. You can use its APIs to create pages dynamically, add data into GraphQL, or respond to events during the build lifecycle.

Every Gatsby Node API gets passed a set of helper functions. These let you access several methods like reporting, or perform actions like creating new pages.

However, what you can do, is to set the tracking ID manually via React Helmet based on the content of your CMS, this would be simpler to achieve. In your createPage function you can do:

createPage({
  path: `/somePath/${node.id}`,
  component: yourComponent,
  context: {
    trackingId: node.trackingId,
  },
})

The trackingId stands for your analytics tracking ID and will be available under props.pageContext.trackingId in your front-end view.

  • Related