Share this post with your friends
In this post, I will show you, how to start node.js with environment variables.
Starting Node.js with Single Environment Variable
Let's say we have an environment variable
API_KEY which has the value
Now we want to it to be available only on our node.js process. Doing that is pretty simple. Basically you start node.js with the environment variable.
For example, run this command from the terminal/console,
$ API_KEY=c3697d975a9a394828289efcfc328c02 node
It opens up node.js REPL command line interface. Now we can print the variable with the following command:
We can execute a single command without going into Node.js REPL interface.
$ API_KEY=c3697d975a9a394828289efcfc328c02 node -e 'console.log(process.env.API_KEY)'
Remember this environment variable is only available to the node.js process you started with that variable.
Starting Node.js with Multiple Environment Variable
You can also include more than one variable at a time.
KEY1=value1 KEY2=value2 KEY3=value3 node
Set Environment Variable through
You can also use
.bashrc file to do that automatically. So you won't have to type in everything everytime.
$ nano ~/.bashrc
Add the following line to the
alias node='API_KEY=c3697d975a9a394828289efcfc328c02 USERNAME=shovon node'
Once you're done, save it. then, open a new terminal and run the following
$ node -e 'console.log(process.env.API_KEY)'
$ node -e 'console.log(process.env.USERNAME)'