How to read environment variables from Node.js
Learn how to read and make use of environment variables in a Node.js program
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 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, which is set to development by default.
Note:
processdoes not require a “require”, it’s automatically available
process.env.NODE_ENV // "development"
Setting it to “production” before the script runs will tell Node that this is a production environment.
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"
You can write the environment variables in a .env file (which you should add to .gitignore to avoid pushing to GitHub), then
npm install dotenv
and at the beginning of your main Node file, add
require('dotenv').config()
In this way you can avoid listing the environment variables in the command line before the node command, and those variables will be picked up automatically.
Note that some tools, like Next.js for example, make environment variables defined in
.envautomatically available without the need to usedotenv.
download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.