Script Valley
REST API Development: Beginner to Production
Testing, Documentation, and Production DeploymentLesson 6.4

Environment variables and config management for APIs

dotenv, .env.example, config module, environment-specific settings, secrets management, never commit secrets, validation with envalid

Environment Variables and Config Management

Hard-coding configuration values (DB URLs, JWT secrets, API keys) in code is a critical security vulnerability and makes deployment inflexible. Use environment variables for all environment-specific and secret values.

The Pattern

npm install dotenv envalid
// config/env.js โ€” validate required vars at startup
const { cleanEnv, str, port, url } = require('envalid');

module.exports = cleanEnv(process.env, {
  NODE_ENV: str({ choices: ['development', 'test', 'production'] }),
  PORT: port({ default: 3000 }),
  DATABASE_URL: url(),
  JWT_SECRET: str({ docs: 'Min 32 chars random string' }),
  REFRESH_SECRET: str()
});
// index.js
require('dotenv').config(); // load .env into process.env
const env = require('./config/env'); // validate immediately
const app = require('./app');
app.listen(env.PORT);

.env.example

# .env.example โ€” commit this, NOT .env
NODE_ENV=development
PORT=3000
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
JWT_SECRET=replace_with_32_char_random_string
REFRESH_SECRET=replace_with_different_32_char_string

Commit .env.example with placeholder values to document what variables are needed. Add .env to .gitignore. Fail fast on startup if required variables are missing โ€” catching config errors at boot is far better than mysterious failures at runtime.

Up next

Deploying a Node.js API to production โ€” Railway and Render

Sign in to track progress

Environment variables and config management for APIs โ€” Testing, Documentation, and Production Deployment โ€” REST API Development: Beginner to Production โ€” Script Valley โ€” Script Valley