Skip to content

Environment Config and Secrets

Beginning of the lesson

Environment Config and Secrets

Keep passwords, API keys, and per-environment settings out of your source code

Big Idea: Your program needs values that change between your laptop and the real server - a database password, an API key, a port number. Hard-coding these into your .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.
By the end you will be able to:
  • read configuration from process.env,
  • store local settings in a .env file and load them with dotenv,
  • keep .env out of Git with .gitignore and 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.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers