Same code, different places
Your API runs on your laptop, in tests and in production — with different ports, databases and keys. Keep code the same and pass settings through environment variables. Check them once at startup, so a missing secret fails loudly instead of at 3 a.m.
A config module
function required(name) {
const value = process.env[name];
if (!value) throw new Error(`Missing environment variable ${name}`);
return value;
}
export const config = {
port: Number(process.env.PORT ?? 3000),
env: process.env.NODE_ENV ?? "development",
databaseUrl: process.env.DATABASE_URL ?? "file:./dev.db",
isProd: process.env.NODE_ENV === "production",
};
console.log(config);
try {
required("STRIPE_KEY");
} catch (e) {
console.log(e.message);
}- Locally, keep values in a .env file (add it to .gitignore!) and load it with node --env-file=.env server.js.
- Commit a .env.example listing the variable names without real values.
- Libraries like Zod can validate the whole config object with clear errors.