Settings such as the port, database password or API keys should not be written in your code. Put them in environment variables.
Reading variables
process.env.PORT — always a string (or undefined). Convert numbers with Number() and give defaults: process.env.PORT ?? 3000.
.env files
Put local settings in a .env file:
PORT=3000 DB_PASSWORD=secret
Load it with either:
node --env-file=.env app.js(built into newer Node versions)- the dotenv package:
import 'dotenv/config'at the top of your entry file
Rules
- Add
.envto .gitignore — never commit secrets - Commit a
.env.examplewith the variable names only - On the server, set real values in the hosting panel or a server
.env - Use
NODE_ENV=productionin production — many libraries run faster and show fewer details
A config module
Read and check all variables in one config.js file, and fail fast at startup if a required one is missing.
Example
// .env (not committed)
// PORT=4000
// NODE_ENV=development
// DATABASE_URL=mysql://root:secret@localhost/shop
// JWT_SECRET=change-me-to-a-long-random-string
// config.js
const required = ['DATABASE_URL', 'JWT_SECRET'];
for (const key of required) {
if (!process.env[key]) {
console.error(`Missing environment variable: ${key}`);
process.exit(1);
}
}
export const config = {
port: Number(process.env.PORT ?? 3000),
isProduction: process.env.NODE_ENV === 'production',
databaseUrl: process.env.DATABASE_URL,
jwtSecret: process.env.JWT_SECRET,
};
// Run: node --env-file=.env app.js
The app starts on port 4000 with the values from .env. If JWT_SECRET is missing it stops immediately with a clear message instead of failing later.