Learn how environment variables work, how to use a .env file safely, what to do if a secret leaks, and why some variables are never truly secret in a web app.

Few mistakes are as common, or as costly, as committing an API key to a public repository. Automated bots scan for new leaks all day, and a stolen key can be abused within minutes.

The fix is simple and worth learning properly: keep configuration and secrets outside your code, in environment variables.

What an environment variable is

An environment variable is a named value that lives outside your program and is handed to it when it starts. Your code asks for it by name, so the same code can run on your laptop, a test server and production with different settings.

config.js
const apiKey = process.env.PAYMENTS_API_KEY;

if (!apiKey) {
  throw new Error("PAYMENTS_API_KEY is not set");
}
config.py
import os

api_key = os.environ["PAYMENTS_API_KEY"]   # raises an error if missing

Failing loudly at startup when a value is missing is a good habit. It is far better than a mysterious error later.

Using a .env file locally

Typing variables into your terminal each time is tedious, so most projects use a .env file during development. A small library loads it when the app starts.

.env
DATABASE_URL=postgres://localhost:5432/dev
PAYMENTS_API_KEY=sk_test_abc123
DEBUG=true
  1. **Add .env to .gitignore immediately,** before the first commit.
  2. **Commit a .env.example** with the names but fake values, so teammates know what to set.
  3. **Never share a real .env over chat or email.** Use a password manager or secrets tool.
The real values never touch Git.

In production, use a proper secrets store

A .env file is fine for development. For production, use the secrets feature of your hosting platform, your CI system or a dedicated secrets manager. These encrypt values, control who can read them, and keep an access history.

A warning about frontend code

If a secret leaks

Assume the worst, and move quickly:

  1. Revoke or rotate the key right away in the provider’s dashboard. This is the step that matters most.
  2. Check usage logs for activity you do not recognize.
  3. Remove it from the code, but know that deleting it from Git history does not make it safe again. The key must be replaced.
  4. Find out how it happened and add a guard, such as a secret scanning tool in CI.

Habits that prevent most problems

  • Use different keys for development and production.
  • Give each key only the permissions it needs.
  • Never print secrets in logs or error messages.
  • Run a secret scanner before every push.