I am using a gatsby-plugin-google-tagmanager plugin for analytics of my site, but later I create another site from the same code base (differentiate its branding based on specific routes), for that, I need to add another GTM tag into my plugin. Now I believe I cannot add any conditions in the gatsby-config file (Please correct me if I am wrong), then How do handle this case? Do I need to add insert script manually using the gatsby-SSR function or is there any other way to resolve it?
{
resolve: "gatsby-plugin-google-tagmanager",
options: {
id: config.gtm,
includeInDevelopment: false,
defaultDataLayer: { platform: "gatsby" },
enableWebVitalsTracking: true,
},
},
I am passing gtm tag as per my build environment via process.env
Your best chance is using environment variables to use a different identifier for each file.
If each project triggers a different environment variable, you will be able to use a different instance of GTM in each build.
After adding:
require("dotenv").config({
path: `.env.${process.env.GATSBY_ACTIVE_ENV}`,
})
Your scripts can look like this:
"scripts": {
"build-site-1": "GATSBY_ACTIVE_ENV=site1 gatsby build",
"build-site-2": "GATSBY_ACTIVE_ENV=site2 gatsby build",
},
Then, because of .env.${process.env.GATSBY_ACTIVE_ENV} you can define a .env.site1 and .env.site2 in the root of your project to define each GTM identifier:
GTM_ID= 1234
Finally, in your gatsby-config.js:
{
resolve: "gatsby-plugin-google-tagmanager",
options: {
id: process.env.GTM_ID,
includeInDevelopment: false,
defaultDataLayer: { platform: "gatsby" },
enableWebVitalsTracking: true,
},
},
The GTM_ID will be the one fired by the build command so each file will have each agnostic configuration.
Tweak the approach to fit your specifications but get the idea of the logic separation.