0

I would like to know how to apply google analytics id for local and production,

I have two ID's, each for local and production. I am using node.js as a backend, and stored the google analytics key in config file using env file.

How to pass:

  • If local, pass google analytics id ga_local;
  • If prod, pass google analytics id ga_pro in node.js in the startup.

.env

ga_local = "UA-XXXX-X",
ga_pro = "UA-YYYY-Y"

config.js

require('dotenv').config();
const config = {
    ga_local: process.env.ga_local,
    ga_pro: process.env.ga_pro
};
module.exports = config;

front end

<script async src='https://www.googletagmanager.com/gtag/js?id=${ga_local}'></script>
Alexis Philip
  • 517
  • 2
  • 5
  • 23
Senthil
  • 961
  • 1
  • 8
  • 21

1 Answers1

0

You can use process.env. NODE_ENV variable and set it while starting the server for development or production accordingly. Refer this: How to set NODE_ENV to production/development in OS X

Akansh
  • 1,715
  • 3
  • 15
  • 34
  • thanks for reply, is it like this `"start": "set NODE_ENV=production node app.js", "dev": "set NODE_ENV=dev node app.js"` in package.json? – Senthil Jul 30 '19 at 07:25
  • Yeah. You got it right. And using `process.env.NODE_ENV` to access the value like `ga_id = process.env.NODE_ENV === 'dev' ? ga_local : ga_pro;` – Akansh Jul 30 '19 at 07:47
  • @Senthil Don't use `set` here, instead try `"start": "export NODE_ENV=production && node app.js"` – Akansh Jul 30 '19 at 08:47
  • this means always set to production right, then how do i set code – Senthil Jul 30 '19 at 08:58