Ash Hogarth
Ash Hogarth

Reputation: 567

Environment Variables and detecting environment NodeJS/React

I've looked into things like dotenv and get the concept of environment variables, the part I am missing is where and when the detection of which variable to use happens. To be specific I'm dealing with the Stripe API key and of course, I want to use the Test API key when I'm developing locally and then the Live API key when I push to production.

So obviously I'll have a .env file with something like;

test_API_KEY=1234
live_API_KEY=5678

But then surely somewhere in my code I need something like

var keyToUse;
if(productionEnvironment){
     keyToUse = process.env.live_API_KEY
}
else if(!productionEnvironment){
     keyToUse = process.env.test_API_KEY
}

Or does like dotenv (or secure dot env) manage that for you? Or is this done with another tool/technique?

Thanks in advance

Upvotes: 1

Views: 236

Answers (2)

Ash Hogarth
Ash Hogarth

Reputation: 567

Ok after a bit more digesting, the problem actually comes from a fundamental misunderstanding of how to use Environment Variables. I was imagining the situation that live environment variables should be in the application (perhaps in a JSON file somewhere), and then used according to what environment the application was in.

But it's actually the case (or at least it appears to me) that you need to set the environment variable, IN THE ENVIRONMENT - not the code! So for example on AWS or Google Cloud, those will then overwrite whatever you are using for local use as @getElementsByName is alluding to with the same naming convention

That way when you develop locally with API_KEY=1234 it gets overwritten on live with API_KEY=4567 and there is no (if environment == live), then do this...

Upvotes: 0

getElementsByName
getElementsByName

Reputation: 131

The dotenv recommends to use a same name of env variable regardless of deploy environment.

For example,

.env (in local)

API_KEY=local_api_key

.env (in test)

API_KEY=test_api_key

The base principle says separation of config from code. (the .env file may be included in .gitignore)

In your way, if some environment is added (like stage-2), some associated code may be added.


If you want to have a set of constant values by deploy environments as code, just create config.local.js, config.test.js.....

consider below code)

let constSet;
switch(process.env.DEPLOY_ENV) {
   case 'local':
      constSet = require('./config.local')
      break; 
...
}

Upvotes: 1

Related Questions