Environment Config and Secrets
Keep passwords, API keys, and per-environment settings out of your source code
.js files is unsafe and inflexible. Environment configuration lets you feed those values in from outside the code, so the same code runs everywhere and your secrets never end up in version control.
- read configuration from
process.env, - store local settings in a
.envfile and load them with dotenv, - keep
.envout of Git with.gitignoreand ship a safe.env.example, - validate config at startup and provide sensible defaults per environment.
1. The problem: secrets in your code
Imagine you connect to a database like this, straight inside your source file:
// db.js -- DO NOT do this
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: 'db.myapp.com',
user: 'admin',
password: 'S3cr3t-Pa55!', // a real password, committed to Git
});
This works on your machine, but it has three serious problems:
- It leaks secrets. The moment you
git commit, that password lives in your repository history forever - even if you delete the line later. Anyone with access to the repo (or a public GitHub mirror) can read it. - It is not portable. Your laptop, a teammate's laptop, and the production server all need different values. Hard-coded strings force you to edit code just to change a host.
- It is hard to rotate. When a key is compromised you want to swap it in seconds, not hunt through source files and redeploy.
Analogy. Think of your source code as a recipe you publish in a cookbook, and your secrets as the key to your house. You would happily share the recipe, but you would never print your house key inside it. Configuration is the sealed envelope you hand to whoever is cooking in your kitchen - it stays with the environment, not with the recipe.