/

How to Read Environment Variables from Node.js

How to Read Environment Variables from Node.js

Learn how to read and utilize environment variables in a Node.js program.

Environment variables are incredibly valuable as they allow us to avoid hardcoding sensitive information, such as API keys, directly into our code and inadvertently pushing it to GitHub.

Modern deployment platforms, including Vercel and Netlify, offer ways to add environment variables through their interfaces, making it even easier to manage these variables.

In Node.js, the process core module provides the env property, which contains all the environment variables set when the process began. For example, the NODE_ENV environment variable is set to development by default.

To access a specific environment variable, you can use the following code:

1
process.env.NODE_ENV // "development"

By setting it to “production” before running the script, you can inform Node.js that it is operating in a production environment. Similarly, you can access any custom environment variable by referencing its name:

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

To simplify managing environment variables, you can store them in a .env file (remember to add it to your .gitignore to prevent accidental pushes to GitHub). Additionally, you can use the dotenv package:

1
npm install dotenv

In your main Node.js file, add the following line at the beginning:

1
require('dotenv').config()

This allows you to avoid specifying environment variables on the command line before running the node command, as the variables will be automatically picked up.

Note that certain tools, such as Next.js, automatically make environment variables defined in .env available without the need for the dotenv package.

tags: [“Node.js”, “environment variables”, “dotenv”, “programming tips”]