---
title: Environments & secrets
summary: Configuration that changes between environments, and credentials that must never leak.
section: shipping
phase: ship
order: 2
last_reviewed: 2026-11-20
---

# Environments & secrets

Leaked API keys are one of the most common (and most expensive) mistakes in agent-built apps. Bots scan public repos for keys within minutes of a push.

## You'll be able to
- Keep config separate from code, per environment
- Store, inject and rotate secrets safely
- Know which values are safe to expose to the browser

## The mental model

Every value your app needs falls into one of three groups. **Config** is anything that differs between deploys (a database address, a hostname). **Secrets** are credentials that must stay private. **Public values** are safe for anyone to see. The Twelve-Factor App gives a simple test for separating config from code: could you open-source the repository right now without exposing any credentials?

Then ask where each value can end up: in the code or git history, in the **browser bundle**, or only on the server at runtime. Secrets belong only in the last place.

## Key concepts
- **Environment variables:** Config injected at runtime (`DATABASE_URL`, `STRIPE_SECRET_KEY`).
- **`.env` files:** Local-only values. **Always gitignored.** Commit a `.env.example` with placeholder values instead.
- **Public vs secret:** Variables prefixed with `NEXT_PUBLIC_`, `VITE_` or `PUBLIC_` are **bundled into browser code**, so anyone can read them. Only non-sensitive values (like publishable keys) belong there.
- **Secret managers:** Platform env settings (Vercel, Railway), GitHub Actions secrets, Doppler, Infisical, 1Password, AWS/GCP Secret Manager.
- **Rotation:** Replacing a key. Do it immediately if a key leaks, and periodically even if it hasn't.
- **Least privilege:** Each key gets the minimum scope it needs (read-only, restricted to certain endpoints, IP-limited).
- **Validation at boot:** Parse env vars with a schema (for example Zod/`t3-env`) so the app fails fast when something is missing.
- **Secret scanning:** GitHub push protection, gitleaks, trufflehog.

> **Note:** In Next.js, `NEXT_PUBLIC_` variables are inlined into the JavaScript bundle when you run `next build`. They are frozen at that moment: changing one later has no effect on an app that is already built, and a build promoted from one environment to another carries the original values. Vite works the same way for `VITE_` variables, and its documentation says plainly that they must not hold sensitive data such as API keys.

## Decisions you make (not the agent)
| Decision | Sensible default | Choose otherwise when… |
|---|---|---|
| Storage | Platform env vars + `.env.local` for dev | Many services/teams → Doppler/Infisical |
| Validation | Typed env schema at startup | — |
| Scanning | GitHub push protection + gitleaks in CI | — |
| Agent access | Agents get dev/test keys only | — |

## What good output looks like

- Secrets are read only in server-side code, and nothing sensitive uses a public prefix
- `.env` files are ignored by git, and `.env.example` lists every required variable with placeholder values
- A typed schema validates the environment at startup and fails with a clear message
- Different keys per environment, each with minimum scope
- Nothing secret appears in logs, error messages or CI output

## Red flags
- Secret keys in a `NEXT_PUBLIC_`/`VITE_` variable
- `.env` committed, or missing from `.gitignore`
- Keys pasted directly into source "temporarily"
- One all-powerful key shared across every environment
- Secrets printed in logs or error messages
- **Common agent mistakes:** putting a key in a public-prefixed variable "so the client component can use it"; committing `.env` or a `.env.local` after copying it; printing environment variables while debugging a build; passing a secret as a command-line argument in a CI step (GitHub's documentation advises against it); promoting a build between environments without realising its public variables were fixed at build time

> **Warning:** If a secret ever reaches git history, **rotate it**. Deleting the file doesn't remove it from history.

## Worked example

**Task:** Add Stripe payments to a Next.js app.

You prompt: *"Add Stripe checkout."* The client component needs a key, so the agent creates `NEXT_PUBLIC_STRIPE_SECRET_KEY` and puts the real secret key in it. It copies `.env.local` to `.env` for convenience and commits both.

**What a good result contains:** the secret key used only in server code (a route handler or server action) and never in a public variable; only the publishable key exposed to the browser; a `.env.example` with placeholders; and a startup check that fails if a required variable is missing.

**The wrong turn:** anything with the `NEXT_PUBLIC_` prefix is inlined into the JavaScript that every visitor downloads, so the secret key is public the moment the site builds. The committed `.env` makes it public in git as well. Fixing the variable name later doesn't help: the key has already been exposed and must be treated as compromised.

**How review catches it:** search the built output for the key's value, and check every variable that has a public prefix. Scan the repository and its history with a secret scanner. Then **rotate the key** (deleting the file doesn't remove it from history), move the secret use to server code, and add the typed schema with separate server and client sections.

## Sample prompts

### Weak vs strong
```compare
## Weak
Check my repo for secrets.
## Why it fails
It names no places to look and no fix, so the agent may grep for a few strings and report that it found nothing.
## Strong
Audit this repo for secrets handling: hardcoded keys, secrets exposed to the
client via public env prefixes, .env files tracked in git (including history),
and secrets in logs. Then add a typed env schema that validates at startup,
split into server-only and client-safe variables, and a complete .env.example.
## Why it works
It lists every place secrets leak (hardcoded keys, public prefixes, tracked .env files including history, logs) and ends with a fix: a validated, split env schema and a complete .env.example.
## What changed
- **Places to look** are named, including git history and logs
- **Public prefixes** (`NEXT_PUBLIC_`, `VITE_`) are checked, because those values reach the browser
- **The fix** is a typed schema that fails at startup
- **Server-only and client-safe** variables are separated
- **`.env.example`** documents what is required
```

### Check the build output
```text
Build the project. Then search the build output (the client bundle and static files) for any value from my .env files and for anything that looks like an API key or token. Report each match with the file and the variable it came from. Do not print the secret values. If there are none, say what you searched and how.
```
*Why it works:* The bundle is exactly what visitors can read, so searching it checks what actually leaked, not what the code intended.

### Respond to a leaked key
```text
A key may have leaked: <describe where>. Don't change anything yet. Write a response plan: how to confirm what the key could access, how to rotate it and revoke the old one, where else it might be (git history, logs, CI output, build artifacts), how to check for misuse, and how to prevent it recurring. Order the steps, and put revocation first.
```
*Why it works:* After a leak, the order matters, and speed matters more than tidiness. Rotating comes before cleaning up history.

### Explain where each variable is used
```text
For every environment variable this project reads, tell me: where it is read (file), whether that code runs on the server or in the browser, whether it can reach the browser bundle, when its value is fixed (at build time or at runtime), and whether it is a secret. Flag any secret that could reach the browser.
```
*Why it works:* "Build time versus runtime" and "server versus browser" are the two facts that decide whether a value leaks, and agents often blur them.

### Review CI for secret handling
```text
Review the GitHub Actions workflows for secret handling: secrets printed to logs, passed as command-line arguments, available to workflows triggered from forks, or stored as long-lived cloud credentials where OIDC is possible. List each finding with file and line. Don't change anything yet.
```
*Why it works:* Workflow files are a common place for secrets to leak, and each of these is a specific, checkable item.

## Check your understanding

```quiz
Q: A variable named NEXT_PUBLIC_API_KEY holds a secret key. Who can read it?
- [ ] Only the server
- [x] Anyone who loads the site, because it is bundled into the browser code at build time
- [ ] Only logged-in users
> Why: Public-prefixed variables are inlined into the JavaScript that visitors download. Secrets must stay in server-only code.

---

Q: You committed a key and removed it in the next commit. What should you do?
- [ ] Nothing, it is gone
- [x] Rotate the key. It is still in git history
- [ ] Rewrite the commit message
> Why: Deleting a file doesn't remove it from history, and bots scan repositories quickly. Treat the key as compromised.

---

Q: Which value is appropriate in a public-prefixed variable?
- [ ] A database password
- [x] A publishable key designed to be public
- [ ] A signing secret
> Why: Only values meant to be public belong in browser code. Check what each key is for.
```

## Checklist

- [ ] The repository could be open-sourced today without exposing a credential
- [ ] Nothing secret uses a public prefix, and I searched the build output to be sure
- [ ] `.env` files are ignored, and `.env.example` lists every variable
- [ ] The app validates its environment at startup
- [ ] Each environment has its own keys with minimum scope
- [ ] A leaked key gets rotated first, then cleaned up

## Go deeper
- [OWASP Secrets Management Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html)
- [gitleaks](https://github.com/gitleaks/gitleaks)
- [The Twelve-Factor App: Config](https://12factor.net/config): storing config in the environment
- [Next.js: Environment variables](https://nextjs.org/docs/app/guides/environment-variables) and [Vite: Env variables and modes](https://vite.dev/guide/env-and-mode): what reaches the browser
- [GitHub: Using secrets in GitHub Actions](https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions)
- [GitHub: Push protection](https://docs.github.com/en/code-security/secret-scanning/introduction/about-push-protection): blocks known secret patterns before they are pushed
- [Security of agentic workflows](/docs/ai-agents/agent-security.md): keeping credentials out of an agent's reach
