In this tutorial, we’ll take a look at how to get and set environment variables in Node.js.
So it’s a obviously a good idea to hold sensitive information like API keys and secrets in environment variables for your server side code.
Generally speaking you would set an environment variable with an export
command on the command line.
export API_KEY=abcd1234
echo $API_KEY
Notice how there must be no space between the environment variable name, the =
assignment operator and the value.
So let’s take a look first at how you would access an environment variable like the one above in Node.js
How to get environment variables in Node.js
console.log(process.env.API_KEY); // abcd1234
Simple as that, we access the env
property on the process object which will contain any exported environment variables.
How to set environment variables in Node.js
One thing to understand about environment variables is that they are set (and used) within the shell or process that exports/creates them.
For this reason, if you’re looking to set an environment variable for use globally then this won’t work.
What you can do is set an environment variable which can be used elsewhere in your code or in any child processes it creates.
process.env.NEW_VARIABLE = '1234abcd';
Another thing you might want to do is set an environment variable for a Node.js script within your code (e.g package.json).
For example, you could set different environment variables for development production.
{
"scripts": {
"serve:dev": "cross-env NODE_ENV=dev node server.js",
"serve:prod": "cross-env NODE_ENV=prod node server.js"
}
}
Although a bit contrived you can see how we can set an environment within our package.json to be used within our Node.js code and alter your code’s behaviour based on the value stored in the environment variable.