How to read environment variables in Node.js

Better Stack Team
Updated on March 11, 2024

In Node.js, you can read environmental variables using the process.env object. This object provides access to the user environment, including environment variables. Here's a simple example of how you can read environmental variables in Node.js:

 
// Accessing a specific environment variable
const apiKey = process.env.API_KEY;

if (apiKey) {
  console.log('API Key:', apiKey);
} else {
  console.error('API Key not found in environmental variables.');
}

When running your Node.js application, you can set environmental variables in the terminal or script before starting the application. For example:

 
# Setting an environmental variable in Linux/macOS
export API_KEY=your_api_key

# Setting an environmental variable in Windows (PowerShell)
$env:API_KEY = "your_api_key"

Then, when you run your Node.js script, it can access the environmental variable using process.env.API_KEY.

Keep in mind the following:

  1. Security Considerations:
    • Avoid hardcoding sensitive information directly in your code. Instead, use environmental variables to store sensitive data like API keys, database passwords, etc.
    • Be cautious about exposing sensitive information unintentionally.
  2. Default Values:
    • It's a good practice to provide default values or check if the environmental variable exists before using it to avoid potential issues.
  3. Environment-specific Configuration:
    • Environmental variables are useful for managing configuration settings in different environments (development, testing, production, etc.).
  4. External Configuration:

    • Tools like dotenv can be used to load environmental variables from a .env file during development. Install it using npm install dotenv, and then include the following line at the beginning of your script:

       
      require('dotenv').config();
      

      Create a .env file in your project directory with key-value pairs:

       
      API_KEY=your_api_key
      

      Now, you can access these variables using process.env as usual.

Remember to handle environmental variables with care, especially when dealing with sensitive information, and follow security best practices.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github