Lesson 21 / 23

Environment Variables

Keep secrets and per-environment settings out of the codebase.

process.env + dotenv

Node exposes environment variables via process.env. In development, the dotenv package loads a local .env file into it — never commit that file.

Reading config with fallbacks

Give every variable a sensible default so the app still runs locally without a .env file.

import 'dotenv/config';

const PORT = process.env.PORT || 3000;
const NODE_ENV = process.env.NODE_ENV || 'development';

app.listen(PORT, () => {
  console.log(`Running in ${NODE_ENV} mode on port ${PORT}`);
});