Native Env Variables
Overview
Hardcoding passwords, API keys, or database URLs directly into your JavaScript files is a catastrophic security vulnerability (especially if you push them to GitHub). Environment Variables solve this. They are secure, hidden variables injected directly into the Operating System's memory before Node.js starts. Node can read them securely at runtime using process.env. Starting in Node.js v20+, Node natively supports .env files without needing third-party packages like dotenv.
Syntax
/* --- THE .env FILE (Never commit this to GitHub!) --- */
// PORT=8080
// DATABASE_URL=postgres://admin:secret123@localhost/mydb
// STRIPE_API_KEY=sk_test_51M
/* --- YOUR JS FILE --- */
// Node automatically loads the OS environment into process.env
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;
// If a critical key is missing, crash the app immediately!
if (!process.env.STRIPE_API_KEY) {
console.error("FATAL ERROR: Stripe API Key is missing.");
process.exit(1);
}
// Starting Node v20.6.0, you can load the file natively:
// $ node --env-file=.env app.jsCommon Pitfalls
- Committing your
.envfile to source control. If you push an AWS or Stripe API key to a public GitHub repository, malicious bots will find it within 5 seconds and rack up $50,000 in charges on your credit card. ALWAYS add.envto your.gitignorefile immediately. - Assuming
process.env.PORTis a Number. Everything insideprocess.envis parsed strictly as a String. If you writeif (process.env.PORT === 8080), it will evaluate tofalsebecause'8080' !== 8080. You must parse it if you need strict equality.
Interview Questions
process.env.NODE_ENV used in Node.js applications?NODE_ENV is the industry-standard environment flag. It is typically set to either 'development' or 'production'. Frameworks like Express read this flag natively: if it is 'production', they aggressively cache templates, strip out verbose error logging, and massively optimize performance.
Real-World Example
Using the Native Node v20+ flag to load environment variables without installing the old dotenv NPM package.
// Package.json script
{
"scripts": {
// The --env-file flag tells Node to read the .env file
// and inject it into process.env before executing server.js!
"start": "node --env-file=.env server.js"
}
}Check Your Knowledge
Test your understanding of Native Env Variables with these quick questions.