user2632190
user2632190

Reputation:

Alternative way to access environment variables in Node.js

I'm trying to store production db and email passwords on environment variables to hide to GitHub users.

I set up my vars using export command on terminal:

$ export DB_PASS=mydbpass

But I can't access via process.env.DB_PASS

I'm not sure this is the correct way. I saw that is possible to access by running:

DB_PASS=mydbpass node server.js

But I'm looking for a more practical way to do this.

Upvotes: 1

Views: 1751

Answers (1)

Mukul Jain
Mukul Jain

Reputation: 1175

Here's a practical way to do this.

First of all, you have ti understand that you have to execute shell file to pass data to Node's process objects, i.e, Environment variables.

Ok, so let's create a shell file where you will store all the env variables. Like this,

#!/usr/bin/env bash
export NODE_ENV='development'
export ENVIRONMENT='development'

export PORT='4000'
export TEST_PORT='4040'

# MongoDB
export MONGO_URL='mongodb://localhost:27017/test'

Let's name this file env.sh.

Now let's say your node app is testApp and you run your app by running npm start, so this is what you need to do now:

testApp~$ . ./env.sh && npm start

What above command is doing, it's running your config shell file and then your node app, so in your node app you can access these fields:

process.env.PORT
process.env.TEST_PORT // and so on, basically whatever you have in env.sh file

I hope everything's clear. Let me know in case of any clarification.

Upvotes: 1

Related Questions