Environment Config with dotenv
6 min read
Environment Config with dotenv
Hard-coding database URLs, API keys, or port numbers into source code is a security risk and makes deploying to different environments painful. The standard solution is to store configuration in environment variables and load them from a .env file during development.
bash
npm install dotenvjs
// src/index.ts — load as early as possible
import "dotenv/config";
import app from "./app";
const PORT = Number(process.env.PORT) || 3000;
const NODE_ENV = process.env.NODE_ENV || "development";
app.listen(PORT, () => {
console.log(`[${NODE_ENV}] Server on port ${PORT}`);
});bash
# .env (never commit this file)
PORT=4000
NODE_ENV=development
DATABASE_URL=postgresql://user:pass@localhost:5432/mydb
JWT_SECRET=super-secret-valueAdd .env to .gitignore immediately. Commit only a .env.example file with placeholder values so team members know which variables are required.
Ready to test yourself?
Practice Express— quiz & coding exercises