Spring Fresh Sale! - Up To 67% OFF BDIX Hosting + Free Domain
Node.js

How to Manage Environment Variables and Secrets Securely in Node.js

Secrets — database passwords, API keys, tokens — should never live in your code. They belong in environment variables or a secrets manager, kept out of your source repository entirely. Getting this right prevents one of the most common and damaging leaks: credentials committed to a repo.

Why not hard-code secrets?

Anything in your code ends up in version control, visible to anyone with repo access and impossible to fully erase from history. A leaked key in a public repo can be abused within minutes. Keeping secrets in the environment separates configuration from code.

Using environment variables

Node exposes them on process.env:

const dbPassword = process.env.DB_PASSWORD;

In development, a .env file loaded by a library like dotenv is convenient — but it must never be committed. Add .env to your .gitignore immediately.

Supplying secrets in production

  • Set real environment variables on the server or in your process manager — for systemd use an EnvironmentFile; for Docker use --env-file or orchestrator secrets.
  • Use a secrets manager for larger setups, so secrets are stored encrypted and access is controlled.
  • Restrict file permissions on any env file so only the app's user can read it.

Good habits

  • Never log secrets — keep them out of your logs.
  • Rotate them periodically and immediately if one may have leaked.
  • Validate required variables at startup so a missing secret fails loudly and early.
  • Use different secrets per environment.

This underpins overall Node.js security.

Frequently asked questions

Is a .env file safe to use?

In development, yes — as long as it is git-ignored and never committed. In production, prefer real environment variables or a secrets manager, and lock down file permissions.

I accidentally committed a secret. What now?

Treat it as compromised: rotate that credential immediately, then remove it from the code. Because it lives in git history, changing the key is what actually protects you, not just deleting the line.

How do I stop the app starting without required secrets?

Check for required variables at startup and exit with a clear error if any are missing. Failing fast beats a subtle runtime failure later when the missing secret is finally used.

Was this article helpful?