Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 133 ยท Security and Cryptography

Configuration, Secrets and Environment

Manage Node.js configuration the 12-factor way - process.env, --env-file, process.loadEnvFile and util.parseEnv, validation at startup, secret handling, redaction and feature flags.

The same program runs on your laptop, in a test pipeline and in production, but a few things must differ each time: which database to connect to, which port to listen on, which API key to use, whether debug logging is on. These are configuration. The golden rule, borrowed from the "twelve-factor app" method, is to keep configuration out of the code and supply it from the environment. Code stays identical everywhere; only the environment changes.

Some configuration is harmless (a port number). Some is dangerous (a database password, a signing key). Those are secrets, and they need extra care: they must never be committed to Git, printed in logs, or sent to the browser. This lesson shows how Node.js reads configuration, how to load .env files with the built-in tools, how to validate everything at startup so a typo fails fast, how to handle secrets, and how to build simple feature flags. It connects to Web Application Security and The process Object.

Environment variables and process.env

Every process inherits a set of named text values from its parent: the environment variables. In Node they appear as the object process.env. Two facts matter immediately:

  • Values are always strings. process.env.PORT is '3000', not 3000. A missing variable is undefined.
  • Assigning converts to a string too. process.env.DEBUG = true stores the text 'true', and process.env.X = undefined stores 'undefined', a classic bug source.
Node.js process.env stores strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Never write if (process.env.APP_DEBUG) and expect 'false' to be falsy: any non-empty string is truthy. Convert explicitly, as the validation section below does.

On a real machine you set variables per command or per environment:

Terminal
# Read-only: shell commands on your own machine
APP_PORT=8080 node server.mjs            # macOS / Linux, one command only
export APP_PORT=8080                     # stays set for this shell session
set APP_PORT=8080                        # Windows cmd
$env:APP_PORT = "8080"                   # PowerShell

In production the variables come from the platform: container settings, a process manager, a systemd unit or your hosting provider's dashboard. Read more about process in The process Object.

.env files

Typing a dozen variables before every run is tedious, so a .env file keeps them as simple KEY=value lines. A .env file is for development convenience, never a place to commit real secrets. Node.js has built-in support, so you no longer need the dotenv package for the common cases.

Terminal
# Read-only: the command line flag, available since Node.js 20.6
node --env-file=.env server.mjs
node --env-file=.env --env-file=.env.local server.mjs   # later files override earlier ones

The flag loads the file before your code starts. If you prefer to load it from inside the program, use process.loadEnvFile(path), or parse text yourself with util.parseEnv(text) (no side effects). The TryIt below writes a sample file into the current directory and loads it. Files live only for one run in our environment, which is exactly what we want for a demo.

Node.js Writing and loading a .env file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two behaviours to remember: the process environment beats the file (so an operator can override a value without editing files), and a missing file throws. The next example shows that error, which is also how you can make a .env file optional.

Node.js loadEnvFile with a missing file (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first call is caught and its message is printed (code ENOENT). The second is not, so the program crashes with the same error and a stack trace. Failing loudly is usually what you want for a required file.

Add .env to .gitignore before the first commit. Commit a .env.example instead, with every variable name and harmless placeholder values, so a new developer knows what to set. A secret that has been committed must be treated as leaked and rotated, even if you delete the file later, because Git history keeps it.

Validate configuration at startup

A misspelled variable or an unparsable port should stop the program immediately with a clear message, not cause a confusing crash an hour later when the code path finally runs. So: read the environment in one place, validate and convert it into a typed object, and pass that object around. The rest of the code never touches process.env.

Libraries such as zod or envalid do this (see Validating Input), but the logic is short enough to write by hand.

Node.js A config loader that validates everything

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Why this design works:

  • Collects every problem before failing, so a deployer fixes all of them in one go.
  • Converts types once: port is a number and debug a real boolean everywhere else.
  • Defaults live in one place and are safe for development, never for secrets: a missing API_KEY must be an error, not a default of "changeme".
  • Object.freeze stops other modules from changing configuration at runtime.
  • In production, let this error crash the process on boot. A deployment that fails immediately is rolled back; one that half-works is a mystery.

Handling secrets

A secret is any value that grants access: passwords, API keys, tokens, signing keys, private keys. Reasonable rules:

  1. Keep them out of the repository, the container image and the front-end bundle. Anything shipped to a browser is public.
  2. Inject them at runtime through environment variables, mounted files (Docker/Kubernetes secrets) or a secret manager (cloud vaults, HashiCorp Vault). Environment variables are simple but visible to anything running as the same user and to child processes; a mounted file with tight permissions is a bit stronger.
  3. Give each environment its own secrets and each service the minimum permissions it needs, so a leak in staging does not touch production.
  4. Rotate them on a schedule and immediately after any suspected leak. Design for rotation from the start (for example accept the old and new key for a while).
  5. Never log them. Redact on the way out.

Secrets leak most often through logs, error reports and console.log(config). A small helper that masks sensitive keys makes that mistake harder.

Node.js Redacting secrets before logging

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The Secret wrapper uses a private field (#value), so even Object.keys or a debugger snapshot shown through util.inspect will not display it by accident. It is a safety net against slips, not a vault: code that calls reveal() still gets the value.

Compare, do not echo

When checking a client-provided secret (an API key in a header), compare in constant time with crypto.timingSafeEqual, as shown in Passwords, scrypt and Tokens. And when a secret is missing, say "API_KEY is required", never print what the value was.

Structuring configuration across environments

Common patterns, from simplest to most flexible:

  • One variable per setting (DATABASE_URL, PORT). Easy to override one at a time, and the 12-factor default.
  • NODE_ENV to select behaviour: development, test, production. Many libraries (Express, for example) switch to faster, quieter paths when it is production. Do not invent more names for it; use separate settings like APP_ENV=staging for finer labels.
  • Layered .env files loaded in order (.env, then .env.local, then the real environment on top), with the real environment always winning, as loadEnvFile does.
  • Structured config files (JSON, YAML) for large, non-secret settings. Read them at startup with import ... with { type: 'json' } or fs, and still let environment variables override specific values.

Avoid sprinkling process.env.SOMETHING through your modules. It hides dependencies, makes tests awkward, and duplicates parsing. Centralise it, as in loadConfig, and inject the resulting object (see Module Patterns for ways to share it).

Feature flags

A feature flag turns behaviour on or off without a code change or redeploy: roll out a new checkout page to 10% of users, switch off an expensive feature during an incident, let beta testers in early. The simplest form is a set of boolean config values; a more useful form decides per user, deterministically, with a hash so the same user always gets the same answer.

Node.js Feature flags with percentage rollout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Flag hygiene matters as much as the mechanism: give flags an owner, remove them once a feature is fully rolled out (old flags are a hidden source of bugs and untested combinations), default to off when the flag service is unreachable, and never use flags to hide secrets or enforce permissions. A flag is a switch for behaviour, not an access-control system.

Common mistakes

  • Treating process.env.X as a boolean or number without converting.
  • Committing .env, or a "temporary" key pasted into source code, then deleting it and forgetting that Git remembers.
  • Giving secrets a development default such as "password" that quietly ends up in production.
  • Putting secrets into the front-end bundle (anything prefixed for the browser is public).
  • Reading process.env at import time in many modules, so tests cannot control it and order of loading matters.
  • Logging the whole config, request headers or error.config objects that contain tokens.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does process.env.APP_DEBUG hold after the assignment process.env.APP_DEBUG = false?

    Values in process.env are always strings. 'false' is a non-empty string, so Boolean('false') is true. Convert explicitly.
  2. 2. A variable is set in the real environment and also in the file loaded by process.loadEnvFile. Which value wins?

    Existing environment variables are not overwritten by the file, so operators can override configuration without editing files.
  3. 3. Why validate configuration once at startup instead of when each value is first used?

    A bad port or missing key should stop the deployment immediately, not crash an unrelated code path later. Converting types once also removes repeated parsing.
  4. 4. You accidentally committed an API key and then deleted it in the next commit. What should you do?

    Anyone with the repository history can read the old commit. Only revoking the key makes the leak harmless.
  5. 5. Why hash the flag name and user id to decide a percentage rollout?

    A hash gives each user the same bucket every time (no flickering between old and new), and the buckets are evenly distributed without storing any state.

Summary

  • Configuration belongs in the environment, not in code. process.env values are always strings, so convert and validate them.
  • Node.js can load .env files itself: --env-file=.env on the command line, process.loadEnvFile(path) in code and util.parseEnv(text) for parsing only. Existing environment variables win over the file, and a missing file throws.
  • Read the environment in one place, validate everything at startup, report all problems together, freeze the result and pass it around.
  • Never commit secrets or .env; commit .env.example. Inject secrets at runtime, give each environment its own, rotate regularly, and redact them in logs.
  • Feature flags change behaviour without redeploys; use a stable hash for percentage rollouts, default to off, and remove old flags.

Next: Compression with zlib