Environment Variables

View saved

Read an environment variable

Provide defaults for local learning.

const port = Number(process.env.PORT) || 3000;
app.listen(port);

Set vars in the shell

Temporary for one command:

PORT=4000 node app.js

Use a .env file locally

Install dotenv for local files. Never commit real secrets.

npm install dotenv

// at top of app.js
import "dotenv/config";

// .env (do not commit secrets)
// PORT=4000
// API_TOKEN=learning-only

Good habits

  • Commit .env.example with fake placeholders
  • Add .env to .gitignore
  • Prefer the host platform's secret store in production
  • Do not put API keys in frontend React code

Comments

One comment per signed-in account. Comments are saved with this page’s URL.