Skip to content
SecurityChapter 36 / 57Beginner6 min read

Secrets Management

The right way to manage environment variables and secrets. Keep API keys out of git, use a .env.example file, and rotate a secret the moment it leaks.

On this page

1. What is this practice?

A secret is any value that lets someone get into your system as you: a database password, an API key, a JWT signing secret, a webhook secret, a .pem private key, a cloud service account JSON.

Code is shared with everyone: teammates, CI, and sometimes the whole world. A secret should only ever reach the machine where the app runs.

2. Why does it matter?

Git history forgets nothing. You committed .env, deleted it in the next commit, but it can still be read in the old commit. Bots scan public repos within minutes and start using the keys.

Secret in codeSecret in env
The key gets copied with every cloneThe key exists only in the deploy environment
After a leak the whole history has to be cleanedAfter a leak only one value is rotated
Dev and production share one keyEach environment has its own key
A new developer does not know what each value is.env.example says what is needed and why
Changing a key needs a new commit and deployChanging a key is just an env update

3. When to follow it

LevelHow importantWhy
Learning projectFrom day oneEven free tier keys, once leaked, cause billing or bans, and the habit is being formed now
Production codeAbsolutely non-negotiableOne leak opens a path to all customer data
Senior levelBuild the system for scanning, rotation and access reviewRemembering the rule is not enough, tooling should enforce it

4. Bad vs good code

Bad

ts
const stripe = new Stripe("sk_live_51Hx...realkey");

export const db = postgres("postgres://admin:SuperSecret123@db.example.com/app");
bash
git add .
git commit -m "add payments"

The key is in the code, and git add . probably picked up .env too.

Good

.gitignore ignores all env files and only lets the example back in:

bash
.env*
!.env.example

.env.example is committed, with empty values and a note on every line:

bash
DATABASE_URL=
STRIPE_SECRET_KEY=
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
CRON_SECRET=

At boot the app checks that every value is present, so a missing key is caught at deploy and not on the first request in production:

ts
import { z } from "zod";

const schema = z.object({
  DATABASE_URL: z.url(),
  STRIPE_SECRET_KEY: z.string().startsWith("sk_"),
  CRON_SECRET: z.string().min(32),
});

export const env = schema.parse(process.env);

What is the difference?

ThingBadGood
Where the key isIn the source codeIn the environment
A new developerGuessesReads .env.example
A missing keyA strange error at runtimeA clear error at boot
Effect of a leakHistory purge and panicRotate one value

What the public prefix means

In Next.js a variable with NEXT_PUBLIC_ (and EXPO_PUBLIC_ in Expo) goes into the browser bundle. That means it is sent to every user. Keep only publishable keys there, never a secret key.

5. How to apply it

Setup in a new project
Ignore .env* in .gitignore and include .env.example
Put every variable's name and a note in .env.example
Validate the env with a schema at boot
Run a secret scanner before commit
Run the same scanner in CI
Production secrets only in the hosting or CI secrets settings

For secret scanning, a tool like gitleaks runs locally before commit and in CI on every pull request. People forget, scanners do not.

If a secret does leak, this is the order:

Leak response
Rotate the secret at the provider (create a new one, disable the old one)
Put the new secret into the app
Purge it from git history
Confirm with the provider that the old secret no longer works
Tell the team the same day: what leaked, when, what was rotated

Why rotate first? Because a purge cannot take the leak back. Anyone who already cloned the repo has the key.

6. Exceptions and common mistakes

When the rule does not apply: publishable keys (like a payment provider's publishable key, or a database anon key when row level security is on) are made to be public. They can go in NEXT_PUBLIC_. Dummy values for local dev are not secrets either, but still keep them in .env, not in code.

Mistake: Only deleting the file after a leak

Why? Even after the delete commit the secret still exists in old commits, and with anyone who cloned earlier.

Better: Rotate at the provider first, then purge the history, then confirm the old key is dead.

Mistake: Adding NEXT_PUBLIC_ to a secret key so it can be called from the client

Why? That key reaches the browser of every visitor inside the JavaScript bundle.

Better: Make the secret call on the server (a route handler or server action) and let the client call only that endpoint.

Mistake: A default password in a seed script, test helper or shell script

Why? These files get committed too, and real credentials often hide in exactly these.

Better: Read an env variable everywhere and give a clear error when it is missing.

Mistake: Pasting a secret into a log or chat

Why? Logs and chat history are stored data that many people can read.

Better: Scrub sensitive keys in the logger and share secrets only through a password manager or secret manager.

7. What to learn before and after

Final quick revision

CheckYes?
.env* and !.env.example in .gitignore
Every variable's name and a note in .env.example
Env validation at boot
Secret scanner at commit and in CI
Only publishable keys in NEXT_PUBLIC_
On a leak, rotate first, purge later