How to read environment variables from Node.js

By

Learn how to read environment variables in Node.js through process.env, set them on the command line, and load a .env file with --env-file or loadEnvFile.

~~~

Environment variables are especially useful because we can avoid typing API keys and other sensible data in the code and have it pushed by mistake to GitHub.

And modern deployment platforms like Vercel and Netlify (and others) have ways to let us add environment variables through their interfaces.

The process core module of Node.js provides the env property which hosts all the environment variables that were set at the moment the process was started.

Here is an example that accesses the NODE_ENV environment variable. Node does not set it by itself, so it’s undefined until you or your hosting platform set it:

Note: process does not require a “require”, it’s automatically available

process.env.NODE_ENV // undefined

Libraries like Express read it and switch to their optimized behavior when the value is production. I explain the whole convention in Node, the difference between development and production.

In the same way you can access any custom environment variable you set.

Here we set 2 variables for API_KEY and API_SECRET

API_KEY=123123 API_SECRET=456456 node app.js

We can get them in Node.js by running

process.env.API_KEY // "123123"
process.env.API_SECRET // "456456"

Load a .env file with Node

You can write the environment variables in a .env file (which you should add to .gitignore to avoid pushing to GitHub).

On a current Node.js version, load that file with the built-in --env-file flag. It has been stable since Node 24.10 and 22.21, and it works on Node 26 too:

node --env-file=.env app.js

If the file might be missing, use:

node --env-file-if-exists=.env app.js

You can also load it from code with process.loadEnvFile():

process.loadEnvFile()
// or: process.loadEnvFile('./config/.env')

That fills process.env the same way the CLI flag does. You do not need a package for the common case.

If you ever need to convert a .env file to JSON or YAML (or back), I made a free env converter for that.

When you still want dotenv

Use dotenv when you are on an older Node version, or when you need variable expansion (dotenv-expand).

npm install dotenv

and at the beginning of your main Node file:

require('dotenv').config()

Note that some tools, like Next.js for example, make environment variables defined in .env automatically available without the need to use dotenv.

If you are still choosing how to install Node itself, see my Node.js installation guide.

Tagged: Node.js · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about node: