Environment Variables

Environment variables are values set outside your code that your app reads at runtime. They are used for:

  • API keys and secrets (never hardcode these in source files)
  • Configuration that differs between environments (development, staging, production)
  • Port numbers, database URLs, feature flags

process.env

Node.js exposes all environment variables on the process.env object. Values are always strings, even if they look like numbers.

console.log(process.env.NODE_ENV); // 'development'
console.log(process.env.PORT);      // '3000' (a string, not a number)

const port = Number(process.env.PORT) || 3000;

Setting variables in the terminal

You can set variables inline when running a command:

PORT=4000 node index.js
NODE_ENV=production node index.js

Or export them for your current shell session:

export PORT=4000
node index.js

These are temporary and disappear when you close the terminal.

.env files and dotenv

For development, store your variables in a .env file in the project root. The dotenv package loads them into process.env automatically when your app starts.

Install dotenv:

npm install dotenv

Create a .env file in the project root:

PORT=3000
NODE_ENV=development
DATABASE_URL=mongodb://localhost:27017/mydb
API_KEY=your-secret-api-key-here

Load it at the very top of your entry file, before anything else that uses the variables:

// ES module syntax (if "type": "module" in package.json)
import 'dotenv/config';

// CommonJS syntax
require('dotenv').config();

// Now process.env has your variables:
const port = Number(process.env.PORT) || 3000;
console.log(`Starting on port ${port}`);

Never commit .env to git

Your .env file contains secrets. Add it to .gitignore:

node_modules/
.env

Create a .env.example file with the same variable names but no real values. Commit this file so other developers know what variables they need to set up:

PORT=3000
NODE_ENV=development
DATABASE_URL=
API_KEY=

Accessing variables in production

Production servers set environment variables directly, not via .env files. Platforms like Heroku, Railway, Render, and Vercel have a settings UI where you enter variable names and values. Your app reads them the same way via process.env.

Validating required variables

Crash early if a required variable is missing, rather than failing mysteriously later in the app:

const required = ['DATABASE_URL', 'API_KEY'];

for (const key of required) {
  if (!process.env[key]) {
    console.error(`Missing required environment variable: ${key}`);
    process.exit(1);
  }
}

Put this check near the top of your entry file, right after loading dotenv.

  • npm : adding dotenv and other packages to your project
  • Project Structure : where to put .env and .gitignore
  • Process : other useful things available on process