Environment Variables in Node.js Without dotenv
Configuration such as database URLs and API keys belongs in environment variables, not in code. Node.js can now load .env files itself.
Loading from the command line
# .env
DATABASE_URL=postgres://localhost:5432/app
PORT=3000
node --env-file=.env src/server.js
# Several files: later ones override earlier ones
node --env-file=.env --env-file=.env.local src/server.js
Use --env-file-if-exists for files that are optional, such as .env.local.
Loading from code
import process from 'node:process';
process.loadEnvFile(); // loads ./.env
process.loadEnvFile('.env.test'); // or a specific file
Variables already set in the real environment are not overwritten, so production values from your host win over a stray .env file.
Validate at startup
Fail fast with a clear message instead of a mysterious error an hour later:
function required(name) {
const value = process.env[name];
if (!value) throw new Error(`Missing required environment variable ${name}`);
return value;
}
export const config = {
databaseUrl: required('DATABASE_URL'),
port: Number(process.env.PORT ?? 3000),
isProduction: process.env.NODE_ENV === 'production',
};
For larger configs, a schema library like Zod gives typed, validated settings in a few lines.
Keep secrets safe
- Add
.envto.gitignore; commit a.env.examplewith placeholder values. - In production, use your platform's secret manager rather than files on disk.
- Read config in one module and import it elsewhere, instead of scattering
process.envthrough the code. - Never send server environment variables to the browser bundle unless they're meant to be public.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.