Ashish Gupta
Ashish Gupta

Reputation: 65

Difference between export SOME_ENV_VAR=KEY and SOMEOTHER_ENV_VAR=KEY in dotenv?

I am relatively new to Node.js. I want to export environment variables from .env file to my javascript files. In order to do that I am using dotenv.

Which method should I use to export the environment variables to my main javascript files ( say- app.js)

export GEOCODER_API_KEY= someKeyXYZ // inside .env file

GEOCODER_API_KEY_1 = someKeyXYZ // inside .env file

One thing to note is that upon console.log(process.env) in the app.js, the GEOCODER_API_KEY_1 shows up as env variable, but not GEOCODER_API_KEY? Why is that. What use is the first one then, since it is not accessible? A more confusing thing is that:

var options = {
  provider: 'google',
  httpAdapter: 'https',
  apiKey: process.env.GEOCODER_API_KEY,
  formatter: null
};  // this works

... // some javascript
console.log(process.env.GEOCODER_API_KEY) //SHOWS UNDEFINED

I basically want to export the API_KEY (unrestricted) safely to my project. Is there a catch that I might be missing?

Upvotes: 0

Views: 1507

Answers (1)

madflow
madflow

Reputation: 8520

The correct way of writing portable variable declarations in an .env file is:

FOO=BAR

This is - when you use dotenv implementations like dotenv.

require('dotenv').config();

console.log(process.env);

When using export in .env in a Unix/Bash environment (what you have probably seen in the wild) - sourcing the file will yield differences concerning the scope of the declared variable:

# .env
export GEOCODER_API_KEY=someKeyXYZ
GEOCODER_API_KEY_1=someKeyXYZ
# main.sh

#!/bin/bash

. ./.env

./subprocess.sh
# subprocess.sh
#!/bin/bash

echo "GEOCODER_API_KEY": $GEOCODER_API_KEY

echo "GEOCODER_API_KEY_1": $GEOCODER_API_KEY_1
./main.sh
GEOCODER_API_KEY: someKeyXYZ
GEOCODER_API_KEY_1:

Upvotes: 1

Related Questions