Back to KB
Difficulty
Intermediate
Read Time
4 min

Managing Environment Variables in Node.js: The Complete Guide

By Codcompass TeamΒ·Β·4 min read

Stop hardcoding secrets. Here's how to do it right.

The Problem

// ❌ NEVER do this
const DB_PASSWORD = 'SuperSecret123!';
const API_KEY = 'sk-live-abc123def456';
const STRIPE_SECRET = 'sk_test_...';

Enter fullscreen mode Exit fullscreen mode

Solution 1: .env Files (The Standard)

# .env file (NEVER commit this!)
DB_HOST=localhost
DB_PORT=5432
DB_NAME=myapp
DB_USER=admin
DB_PASSWORD=secret123
API_URL=https://api.example.com
API_KEY=abc123
NODE_ENV=development
PORT=3000

Enter fullscreen mode Exit fullscreen mode

// Load .env (at the very top of your app, before anything else)
import 'dotenv/config';
// or: require('dotenv').config();

// Access variables
const dbHost = process.env.DB_HOST;
const port = process.env.PORT || 3000;

Enter fullscreen mode Exit fullscreen mode

Solution 2: Validation with Zod

// config.js β€” Validate all env vars at startup
import { z } from 'zod';

const envSchema = z.object({
  NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
  PORT: z.coerce.number().default(3000),
  DATABASE_URL: z.string().url(),
  API_KEY: z.string().min(1),
  JWT_SECRET: z.string().min(32),
  REDIS_URL: z.string().optional(),
  LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
});

export const config = envSchema.parse(process.env);

// If any required variable is missing or invalid β†’ crashes at startup!
// This is GOOD β€” fail fast instead of failing randomly during runtime.

Enter fullscreen mode Exit fullscreen mode

Solution 3: Multi-Environment Config

πŸŽ‰ Mid-Year Sale β€” Unlock Full Article

Base plan from just $4.99/mo or $49/yr

Sign in to read the full article and unlock all 635+ tutorials.

Sign In / Register β€” Start Free Trial

7-day free trial Β· Cancel anytime Β· 30-day money-back