Keeping secrets out of your code and your Git history
Almost every project I take over has at least one password in the code. A database URL in a config file, a payment gateway key in a front-end bundle, an SMTP password in a commit from three years ago. None of it was malicious. It was just quicker at the time.
Leaked keys are one of the most common ways small systems get compromised, and bots scan public repositories for them constantly. Here is the setup I use so it doesn’t happen.
Settings live in the environment, not the code
Anything that changes between your laptop and production, or that would hurt if it leaked, goes in environment variables: database URLs, API keys, SMTP passwords, JWT secrets, payment gateway credentials.
For local development and simple servers, a .env file holds them:
# .env (never committed)
NODE_ENV=production
MONGO_URL=mongodb://app:long-random-password@mongo:27017/acme?authSource=admin
REDIS_URL=redis://redis:6379
JWT_SECRET=paste-64-random-characters-here
SMTP_PASS=...
Commit an example file with the names but no real values, so the next developer knows what to fill in:
# .env.example (committed)
NODE_ENV=development
MONGO_URL=mongodb://localhost:27017/acme
REDIS_URL=redis://localhost:6379
JWT_SECRET=
SMTP_PASS=
And make sure Git ignores the real one, from the very first commit:
# .gitignore
.env
.env.*
!.env.example
Generate secrets properly instead of typing them: openssl rand -base64 48 gives you a strong random value.
Check every setting at start-up
An app that starts with a missing setting and fails later, on the first payment, is far worse than one that refuses to start. Validate the environment once, at boot. In NestJS:
// env.ts
import { z } from 'zod';
const Env = z.object({
NODE_ENV: z.enum(['development', 'production', 'test']),
MONGO_URL: z.string().url(),
REDIS_URL: z.string().url(),
JWT_SECRET: z.string().min(32),
SMTP_PASS: z.string().min(1),
});
export type Env = z.infer<typeof Env>;
export const validateEnv = (config: Record<string, unknown>) => Env.parse(config);
// app.module.ts
ConfigModule.forRoot({ isGlobal: true, validate: validateEnv });
If JWT_SECRET is missing or too short, the app now stops immediately with a clear message naming the problem.
Front-end code is public
Anything in your React, Angular or Vue bundle is readable by every visitor. Bundlers often expose variables with prefixes like VITE_ or NEXT_PUBLIC_, and those values end up in the JavaScript. That’s fine for a public key meant for browsers (a maps key restricted to your domain, a payment gateway’s publishable key). It is never fine for a secret key. If the browser needs to do something that requires a secret, the browser calls your API and the API uses the secret.
Docker: pass secrets at run time
Don’t bake secrets into images with ENV or ARG in a Dockerfile. They stay readable in the image layers forever, including in any registry you push to. Pass them when the container starts:
# docker-compose.yml
services:
api:
build: ./api
env_file: .env
Add .env to .dockerignore as well, so COPY . . never copies it into the image.
When a secret has already been committed
This is the part people get wrong. Deleting the line and committing again does not help. The secret is still in the history, and if the repository was ever public or shared, assume it’s been copied.
Do these in order:
- Rotate the secret first. Create a new key or password in the service’s dashboard, update production, and revoke the old one. This is the step that actually protects you, and it should happen within minutes, not after the clean-up.
- Check whether it was used. Look at the service’s logs or billing for activity you don’t recognise.
- Then clean the history, if the repository will stay shared.
git filter-repois the current tool for this:
pip install git-filter-repo
# Replace the leaked value everywhere in history:
echo 'sk_live_the_leaked_key==>REMOVED' > replacements.txt
git filter-repo --replace-text replacements.txt
git push --force --all
Rewriting history changes every commit hash, so everyone with a copy has to re-clone. That’s why rotating comes first: cleaning history is housekeeping, rotating is protection.
Catch it before it happens
- Turn on secret scanning where your code is hosted. GitHub’s push protection blocks pushes that contain recognisable keys from many providers.
- Scan old repositories once with a tool like gitleaks (
gitleaks detect) to find what is already there. - Use separate keys for development and production, so a leaked development key can’t touch real data or real money.
- Give each key the least access it needs. A key that can only send emails is much less dangerous than one that can manage your whole account.
Summary
- Secrets go in environment variables, never in code
- Commit
.env.example, ignore.env, from day one - Validate every setting at start-up and fail fast
- Nothing secret in front-end bundles or Docker images
- Leaked? Rotate first, check usage, then clean history
- Turn on secret scanning and keep development and production keys separate