2026-09-18 · Q&A guide

Why Store Secrets in Environment Variables in Node.js

Learn why secrets belong in env vars, how to set them, and best practices for Node.js apps.

Why Env Vars Beat Config Files

Secrets in plain files are easy to commit, share, or expose through version control. Environment variables are isolated to the runtime environment, so the code never contains the secret. This reduces accidental leaks and lets you rotate keys without redeploying code. In CI/CD pipelines, secrets can be injected by the orchestrator, keeping them out of the repository entirely.

Typical Secrets in a Node.js App

- Database credentials - OAuth client IDs & secrets - JWT signing keys - Session store secrets - Third‑party API keys

All of these are read via `process.env` at runtime, keeping the values out of the source tree.

Setting an Env Variable

On Unix shells: ```bash export JWT_SECRET="super‑secret‑key" node app.js ``` In Docker or Kubernetes you pass `-e JWT_SECRET=…` or define it in a secret store. For local development, use a `.env` file with the dotenv package: ```bash # .env JWT_SECRET=super‑secret‑key ``` ```js require('dotenv').config(); const secret = process.env.JWT_SECRET; ```

require('dotenv').config();
const jwtSecret = process.env.JWT_SECRET;
const sessionSecret = process.env.SESSION_SECRET;

Best Practices for Secret Management

1. **Never hard‑code** secrets in source. 2. Use a secrets manager (AWS Secrets Manager, HashiCorp Vault, GCP Secret Manager) for production. 3. Rotate keys regularly and keep old keys for graceful revocation. 4. Store only the minimal required scope; use separate secrets for different services. 5. Protect env files with file‑system permissions and exclude them from VCS (`.gitignore`).

Converting a Config File to Env Vars

If your guide uses `config.js`: ```js module.exports = { jwtSecret: 'my‑secret' }; ``` Replace it with: ```js module.exports = { jwtSecret: process.env.JWT_SECRET }; ``` Then set `JWT_SECRET` in the environment as shown above. This keeps the same API while moving the value out of the codebase.

Takeaway: Keep secrets out of code by storing them in environment variables, and manage them with a dedicated secrets service for production.

People also ask

Can I use a .env file in production?

Only for local or staging. In production, inject secrets via the deployment platform or a secrets manager.

What if I need multiple JWT secrets?

Use distinct env vars like `JWT_SECRET_USER`, `JWT_SECRET_ADMIN` and load them separately.

Do I need to restart the app after changing an env var?

Yes, the process reads env vars at startup; restart to apply changes.

Inspired by a public discussion on Stack Overflow. This article is an original explanation for learners.

← All posts