Node.js & APIs · 16 min · 140 XP
Configuration and secrets
Read configuration from the environment, check all of it at startup, and keep secrets out of code, logs and error messages.
The same code runs on your laptop, in CI and in production. What differs is configuration: the database URL, the port, API keys, which email provider to use. Keep it out of the code and read it from the environment, so deploying to a new place means setting variables rather than editing files. Locally, a git-ignored .env file fills the environment; next to it, a committed .env.example lists every variable's name with no real values, so a new teammate knows what to set.
Every environment variable is a string, or missing. PORT=3000 arrives as "3000", and FEATURE_BETA=false arrives as "false", which is truthy, so if (process.env.FEATURE_BETA) turns the feature on. Parse each value deliberately: numbers with Number() and a range check, booleans by comparing to "true", lists by splitting.
const config = loadConfig(process.env); // throws with every problem at once const server = createServer(app(config)); server.listen(config.port);
Fail fast, and fail completely. Check every value at startup, before the server accepts a request. A missing secret discovered at 3am by the first user who triggers a password reset is far worse than a deploy that refuses to start. And report all the problems in one error: fixing one variable per failed deploy is how a five-minute fix becomes an hour.
A secret must never appear in an error message, a log line or the client bundle. Say which variable is wrong and why ("SESSION_SECRET must be at least 32 characters"), never what it contains. And check your framework's rule for which variables reach the browser: in Vite anything prefixed VITE_ is compiled into public JavaScript, where anyone can read it.
Loading your workspace…