Environment Variables

Node js 8 min min read Updated: Mar 30, 2026 Advanced
Environment Variables
Advanced Topic 1 of 8

Environment Variables in Node.js

In real-world applications, sensitive information like database credentials, API keys, and secret tokens should never be hardcoded inside your source code. Instead, these values should be stored securely using environment variables.

Environment variables allow you to configure your application dynamically based on the environment (development, staging, production) without changing the code. In Node.js, the most common way to manage environment variables is by using the dotenv package.

Key Concept: Environment variables store configuration and sensitive data outside the codebase, improving security and flexibility.

What are Environment Variables?

Environment variables are key-value pairs stored outside your application code. They provide configuration values that your application can access during runtime.

Examples of environment variables include:

  • Database connection URL
  • API keys
  • JWT secret keys
  • Application port
  • Environment type (development, production)

Why Use Environment Variables?

  • Security: Keeps sensitive data out of source code
  • Flexibility: Easily switch configurations across environments
  • Maintainability: No need to change code for configuration updates
  • Best practice: Standard approach in modern backend development

What is dotenv?

dotenv is a Node.js package that loads environment variables from a .env file into process.env.

This makes it easy to manage environment variables during development without relying on system-level configuration.

Installing dotenv

Install dotenv using npm:

bash npm install dotenv

Creating a .env File

Create a file named .env in your project root:

env PORT=3000 DB_URL=mongodb://localhost:27017/mydb JWT_SECRET=mysecretkey

Each variable is defined as a key-value pair.

Using dotenv in Your Application

Load environment variables at the start of your application:

javascript require("dotenv").config();

After this, you can access variables using process.env.

Accessing Environment Variables

javascript const port = process.env.PORT; const dbUrl = process.env.DB_URL; console.log("Server running on port:", port);

This allows your application to use dynamic configuration values.

Example: Using Environment Variables in Express

javascript require("dotenv").config(); const express = require("express"); const app = express(); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });

Environment-Based Configuration

Applications often behave differently based on environment:

env NODE_ENV=development
javascript if (process.env.NODE_ENV === "production") { console.log("Production mode"); } else { console.log("Development mode"); }

Handling Missing Environment Variables

Always validate required environment variables to avoid runtime errors:

javascript if (!process.env.JWT_SECRET) { throw new Error("JWT_SECRET is not defined"); }

Best Practices for Environment Variables

  • Never commit .env file to version control
  • Use .env.example to document required variables
  • Keep secrets secure in production (use secret managers)
  • Use meaningful variable names
  • Validate required variables at startup

.env vs System Environment Variables

Feature .env File System Environment
Usage Development Production
Storage Project file OS-level configuration
Security Less secure if committed More secure
Ease of Use Easy Requires setup

Using Multiple Environment Files

You can create multiple environment files for different environments:

  • .env.development
  • .env.production
  • .env.test

This helps manage different configurations easily.

Security Considerations

  • Never expose secrets in frontend code
  • Do not log sensitive environment variables
  • Use secret managers in cloud environments
  • Rotate sensitive keys regularly

Common Mistakes

  • Committing .env file to Git
  • Hardcoding secrets in source code
  • Not validating required variables
  • Using inconsistent variable names
  • Exposing environment variables to frontend unintentionally

Real-World Use Cases

  • Database connection strings
  • API keys for third-party services
  • JWT authentication secrets
  • Application ports and URLs
  • Feature flags and configuration toggles

Conclusion

Environment variables are a fundamental part of secure and scalable application development. By using tools like dotenv, you can manage configuration easily during development and keep sensitive data safe.

Following best practices for environment variables ensures your application remains secure, flexible, and production-ready.

Quick Summary: Environment variables allow secure and flexible configuration management in Node.js by keeping sensitive data outside the codebase.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators