All jobs

Validate Environment Variables With Zod in a Next.js App

Yes. An agent finds every process.env read, parses them with one Zod schema at start-up, proves a missing key fails the build, and opens a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent starts by finding every place the environment is read, because a schema that misses one variable gives false confidence. In a repository laid out like nextjs/saas-starter, there are five: POSTGRES_URL in lib/db/drizzle.ts and drizzle.config.ts, STRIPE_SECRET_KEY and BASE_URL in lib/payments/stripe.ts, AUTH_SECRET in lib/auth/session.ts and STRIPE_WEBHOOK_SECRET in app/api/stripe/webhook/route.ts. Four of those reads end in a ! non-null assertion; only drizzle.ts checks and throws. .env.example lists the same five names, lib/db/setup.ts writes .env for a new developer, and package.json already has zod 3.24 for the form actions in app/(login)/actions.ts. There is no test script, so proof has to come from next build and a script.

The schema goes in one new file, lib/env.ts: a z.object with POSTGRES_URL as z.string().url(), STRIPE_SECRET_KEY as a string starting with sk_, STRIPE_WEBHOOK_SECRET starting with whsec_, BASE_URL as a URL, and AUTH_SECRET with a minimum length, parsed once with safeParse(process.env) and thrown as one message that names every missing or malformed key, not just the first. The file imports server-only, which package.json already has, so a client component that imports it fails at build rather than shipping a secret. The five reads become imports of env, and the ! assertions go away with them.

Two files need care rather than a find-and-replace. drizzle.config.ts runs under drizzle-kit, outside Next.js, so it keeps a plain process.env.POSTGRES_URL read but gains the same dotenv load drizzle.ts already does, and the description says why it is not routed through lib/env.ts. And lib/db/setup.ts writes the .env file from prompts; the agent leaves it alone but adds a line to .env.example saying the app validates these at start-up, so a developer who skips the script learns the names from the error rather than from a crash deep in Stripe.

In its sandbox the agent runs pnpm install and pnpm build with a complete .env to see the build green, then removes AUTH_SECRET and builds again to capture the failure, which must name the key, and quotes that output. It also writes a short tsx script that imports lib/env.ts with a malformed BASE_URL, runs it once to show the message lists both problems when two are present, and deletes the script. The pull request says that Next.js evaluates lib/env.ts when the first server module imports it, so the error appears at build in next build and at the first request in next dev, and never in the browser.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Validate this Next.js app's environment variables with Zod. Grep for every process.env read first, and read .env.example, lib/db/drizzle.ts, drizzle.config.ts, lib/payments/stripe.ts, lib/auth/session.ts, app/api/stripe/webhook/route.ts, lib/db/setup.ts and package.json. Write lib/env.ts with one z.object schema for every variable, with a url check on POSTGRES_URL and BASE_URL, prefix checks on the Stripe keys and a minimum length on AUTH_SECRET, parsed once with safeParse and thrown as a single message naming every bad key; import server-only at the top. Replace each process.env read and its non-null assertion with an import from lib/env.ts, except drizzle.config.ts, which runs under drizzle-kit; give it the same dotenv load and say why. Run pnpm install and pnpm build with a full .env, then remove AUTH_SECRET and build again to capture the failure. Open a pull request quoting both builds.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

What comes back is a pull request with one new file, lib/env.ts, and six edited ones: the four modules that read secrets now import env, drizzle.config.ts loads dotenv and keeps its direct read, and .env.example gains a sentence. No dependency is added, since Zod and server-only are already in package.json. The description quotes pnpm build passing with a full .env and failing with AUTH_SECRET removed, with the thrown message naming the key.

The description also lists the five variables, the check each one has and the file it was read from, so a reviewer can confirm the schema matches .env.example without grepping again. The tsx run with two bad values at once is quoted to show the error names both.

Before merging, a reviewer decides whether BASE_URL should be optional with a http://localhost:3000 default, which the setup script writes today, and whether the Stripe prefix check should accept sk_live_ and sk_test_ only or any sk_ key.

Run it on every pull request

Once the schema is in, the thing to keep is that no new process.env read appears outside it. An automation in the Project with a github trigger on pull_request.opened and pull_request.synchronize and a prompt that greps the diff for process.env starts a run per push: a read outside lib/env.ts and drizzle.config.ts gets a review comment on that line naming the schema file, and a variable the diff adds to .env.example without a schema entry gets the same.

Only work by an owner, member or collaborator fires the trigger; a pull request from a fork never does. Each run reads that pull request's branch in its own sandbox, so a review on one pull request never sees another's .env.

The use case this job follows, with its automation and trigger: Review every pull request.

Why run it on Rush?

A ! after process.env.STRIPE_SECRET_KEY is a promise the deploy will keep, and the first time it does not, the error comes from Stripe's client minutes later with no key named. Validating at start-up is a small change, but the work is finding every read and knowing which files run outside Next.js. In a Rush sandbox the agent greps before it writes, keeps the one file that runs under drizzle-kit on its own path, and proves the failure mode with a build that is missing a key.

The record of the run keeps both builds and the two-error script run, and the pull request quotes them, so the reviewer sees the message a teammate will see at the next bad deploy rather than a schema and a hope. Across every Next.js app a team runs, the same request runs in parallel, one sandbox and one pull request each.

Frequently asked questions

Why not use t3-env or another env library?

The app already has Zod and server-only in package.json, and five variables need one object schema. A new dependency would add a second way to declare them. The pull request keeps it to one file the team owns and can read in a minute.

What about drizzle.config.ts?

drizzle-kit loads that file itself, outside the Next.js build, so importing lib/env.ts with its server-only import would fail there. It keeps a direct process.env read and gains the same dotenv load that lib/db/drizzle.ts has, so pnpm db:migrate works from a fresh clone. The description explains the exception.

When does the validation run?

When the first server module imports lib/env.ts: at build in next build, because the pages that import Stripe and the database are prerendered or compiled then, and at the first request in next dev. The pull request quotes a build failing with the key named. Nothing runs in the browser, which server-only enforces.

Does a missing key still crash at runtime on Vercel?

It fails the build instead, before the deploy goes live, with every missing or malformed key in one message. That is the point: the failure moves from a Stripe call in production to the build log, where the variable names are listed.

More Zod jobs

More jobs like this: Review every pull request

Keep reading