Skip to main content

How to read environment variables in Node.js?

1 min read

Older Article

This article was published 8 years ago. Some information may be outdated or no longer applicable.

Sometimes you need Node.js to behave differently depending on where it’s running. A classic case: more verbose debugging in development, less noise in production. That kind of information typically lives in environment variables.

Providers like DigitalOcean hand you API keys, usernames, and passwords through environment variables. Secrets used for hashing (say for JWT tokens) should live there too.

To read an environment variable, grab it from the process.env object. The properties on that object mirror your environment variables.

You can see what’s available by creating a tiny script:

console.log(process.env);

Run that and it’ll dump every environment variable Node.js can see.

On *nix systems, you can create a new variable and access it like this:

(You can do the same on Windows, obviously.)

$ export SECRET='h3ll0'

Then grab it in code:

console.log(process.env.SECRET); // h3ll0

You’re not limited to logging these values out. Use them wherever you need them in your application.