Builder's DayFree, on demandWatch the talks

API key works locally but is missing after deployment: where do production secrets go?

Locally, your API key comes from a .env file that Git ignores, so the deployed app never receives it. Production secrets go in your host's environment variable settings (a dashboard page or a CLI command) under the exact name your code reads, set for the environment you deployed (many hosts, such as Vercel and Netlify, hold separate values for production and previews). Then deploy again, because on Vercel, Netlify and many other hosts a changed variable applies only to new deployments. Keep the key out of variables with a public prefix such as NEXT_PUBLIC_ or VITE_, which are copied into browser JavaScript at build time. On Prisma Compute, the app reads the key through its service input, and npx prisma@latest project env add PAYMENTS_API_KEY --role production stores the value for the next deploy.
By Gregory Boch10 min read

Your app reads the key from the environment (process.env, or import.meta.env in Vite), and on your machine something fills that in from a .env file: Next.js loads it into process.env, Vite loads it into import.meta.env (and exposes only VITE_ values to browser code), and plain Node.js apps use dotenv or node --env-file. That file is in .gitignore, so it isn't in the repository your host deploys from. The deployed app starts with only the variables the host gives it, and the key isn't one of them until you add it in the host's settings and deploy again.

We make Prisma Compute and Prisma Postgres. The fix below works on any host. Every host and framework behavior on this page links to its documentation, checked on October 22, 2026.

Why the key is there locally and missing in production

A .env file is a convenience for development. Git doesn't commit it, so a host that builds from your repository never sees it. In production, variables come from the platform: Vercel, Netlify, Render, Railway and Fly.io each store them per project, service or app and pass them to your code as environment variables.

TypeScript doesn't catch the gap. With @types/node, process.env.PAYMENTS_API_KEY has the type string | undefined (process.d.ts), and a non-null assertion such as process.env.PAYMENTS_API_KEY! satisfies the compiler without supplying a value. The first sign is often a 401 from the API you call, or a client library that throws because its key is undefined.

Find which check fails

What you see points to the cause. Run the check before you change anything.

What you seeLikely causeCheck
undefined in server code on every requestThe variable isn't set on the host, or is set under a different nameThe host's variable list for that project or service. Names are case-sensitive.
Works in a preview deployment but not in production, or the reverseThe variable is set for one environment onlyThe environments or deploy contexts the variable applies to
Still undefined after you added itThe running deployment is older than the changeWhether a deployment finished after you saved the variable
undefined in browser codeThe code runs in the browser, where server-only variables don't existWhether the code runs in a client component or a Vite client module
The build fails, or a public value is empty in the browserThe variable isn't available to the buildThe variable's scope (build or runtime) and where the build runs
A public value is empty only in deploys built by CIThe CI job doesn't pass the secret to the build stepThe workflow's env: block for the build step
The app exits at startup with an error about a missing .env fileThe start script runs node --env-file=.env and the file isn't on the serverThe start script in package.json

The last row has a specific cause: Node.js throws when the file passed to --env-file doesn't exist. Use --env-file-if-exists=.env (Node.js 22.9 or newer, no longer experimental since 22.21 and 24.10) in a script that also runs in production, or drop the flag there. When both the environment and the file set a variable, Node.js keeps the environment's value.

How to fix it

These steps work on any host. Replace PAYMENTS_API_KEY with your variable names.

1. List every variable the code reads

Search the code for environment reads and compare the list with your .env file:

git grep -nE "process\.env|import\.meta\.env"

Without a path, git grep searches every tracked file, so it finds reads in app/, src/ or anywhere else. The pattern also matches bracket access (process.env["PAYMENTS_API_KEY"]) and destructuring (const { PAYMENTS_API_KEY } = process.env), so read each match for the names it uses.

Check the exact spelling, including case and prefix. PAYMENTS_API_KEY and PAYMENT_API_KEY are different variables, and a host integration can add a variable under a name of its own choosing.

2. Add the variables on the host, for the right environment

Set each variable where the host expects it, for the environment the failing deployment belongs to. Hosts with preview or staging environments (Vercel, Netlify, Railway and Prisma Compute, for example) keep separate values per environment, so a key saved only for previews is missing in production.

These hosts are ordered alphabetically:

HostWhere to set itWhen a change takes effect
Fly.iofly secrets set PAYMENTS_API_KEY=...Immediately: the command updates and restarts each Machine. With --stage, when Machines are next started or updated, for example by fly deploy. Runtime secrets aren't available while Fly.io builds the image, which has separate build secrets.
NetlifyProject configuration, Environment variables, or netlify env:setAfter a new build and deploy. On Pro and Enterprise plans, a variable can be limited to scopes (Builds, Functions, Runtime, Post processing), so a Functions-only key isn't available to the build.
Prisma Computenpx prisma@latest project env add PAYMENTS_API_KEY=... --role production, with the app reading the key through its service input (details below)On the next deploy. Saving a variable doesn't change existing deployments or start a deploy.
RailwayThe service's Variables tabAfter you review and deploy the staged changes. Variables are available to the build and to the running service.
RenderThe service's Environment page in the dashboardYour choice when saving: rebuild and deploy, redeploy the existing build, or save only and apply on the next deploy.
VercelProject settings, Environment Variables, or vercel env addOnly on new deployments. Choose Production, Preview (all branches or one) or Development for each variable.

Other hosts and setups follow the same pattern:

  • Heroku: heroku config:set PAYMENTS_API_KEY=.... Setting a config var restarts the app and creates a new release.
  • Docker: pass variables when the container starts, with docker run --env or --env-file (docker run reference). Don't set secrets with ENV or ARG in the Dockerfile: Docker's docs say they persist in the final image.
  • Kubernetes: store the key in a Secret and reference it from the container's env with secretKeyRef (Kubernetes docs).
  • Amazon ECS: reference the Secrets Manager secret in the task definition's secrets list and give the task execution role permission to read it. The container receives the value when it starts, so after rotating the secret, launch a new task or force a new deployment (Amazon ECS docs).
  • A VM with systemd: EnvironmentFile= reads variables from a file outside the app directory. For secrets, systemd's documentation recommends LoadCredential=, which passes them as files, because environment variables are inherited by child processes.

3. Keep the key in server code

A public prefix publishes the value. Next.js replaces process.env.NEXT_PUBLIC_* references with their values during next build and includes them in the JavaScript sent to the browser. Vite does the same for VITE_* variables and says they shouldn't contain API keys. If browser code needs the result of an API call, call the API from a route handler, server action or backend endpoint that reads the unprefixed variable, and return only the data the page needs.

Build-time inlining also explains a public value that stays empty or old in the browser. Next.js reads NEXT_PUBLIC_ values from the environment where next build runs and doesn't pick up later changes, so the build needs them and you have to rebuild after changing one. Server-only variables are read when the code runs: in Next.js, a page that renders per request reads process.env at that point.

If a CI job runs the build, map each value the build needs into the build step. In GitHub Actions, a step gets a secret only through the secrets context, and a secret that isn't set evaluates to an empty string instead of failing the job:

- run: npm run build
  env:
    NEXT_PUBLIC_MAPS_KEY: ${{ secrets.NEXT_PUBLIC_MAPS_KEY }}

4. Redeploy and check the deployment, not the dashboard

Start a new deployment after saving the variables, then confirm the running code sees them without printing the value. Log whether the variable is set, or call the code path that uses it and check for a successful response:

console.log("PAYMENTS_API_KEY set:", Boolean(process.env.PAYMENTS_API_KEY));

A variable that appears in the host's list only proves the name exists in that environment. It doesn't prove the deployment you're testing was created after you saved it, or that the value is the right key.

5. Fail at startup instead of on the first request

Read required variables once, in a module that server code imports, and stop with the variable's name when one is missing:

src/env.ts
function requireEnv(name: string): string {
  const value = process.env[name];
  if (!value) {
    throw new Error(`Missing environment variable: ${name}`);
  }
  return value;
}

export const paymentsApiKey = requireEnv("PAYMENTS_API_KEY");

The error names the variable and never prints its value. In Next.js, a module imported by a page that is prerendered during next build runs this check during the build, so set the variable for the build as well or import the module only from code that runs per request.

Setting production secrets on Prisma Compute

Prisma Compute hosts TypeScript apps built for Node.js, Bun or Next.js; deployed apps run on Bun. Prisma Compute fits when you want a missing key to stop the deploy instead of reaching production as undefined: in a Prisma Composer app, the deploy fails and names any variable bound with envSecret that is set neither on the platform nor in the deploying shell (Deploying). Compute doesn't require Prisma ORM or Prisma Postgres, so the rest of this section applies to any app you deploy there.

On Compute, the fix has two parts, because the code reads the key differently. The CLI's deploy command, deploy on push and the Deploy Button all deploy a Prisma Composer app; only the REST API, whose endpoint is marked experimental, deploys without one (Deployments). In a Composer app, application code doesn't read process.env, so when you move an existing app over, its process.env reads become service input (Compute FAQ).

First, declare the key as a secretString() field of the service's input, bind it in module.ts with envSecret("PAYMENTS_API_KEY"), and read it with service.input() (Service input). Your code receives a box that redacts the value in logs and JSON, and .expose() returns it where you pass it to the API client.

Then store the value that binding names, as a project environment variable. Variables come in three layers: production, preview for every preview deploy, and overrides for a single preview branch. With only the name, the CLI reads the value from a variable of the same name in your shell, so export it first (for example from your secret manager's CLI) and the key doesn't appear in the command. With the production key exported as PAYMENTS_API_KEY, run:

npx prisma@latest auth login
npx prisma@latest project link <project-id-or-name>
npx prisma@latest project env add PAYMENTS_API_KEY --role production
npx prisma@latest project env list --role production

Every preview deploy receives the preview value, so give previews a separate test or restricted key, not the production one. Export that key as PAYMENTS_API_KEY in the same shell, then run:

npx prisma@latest project env add PAYMENTS_API_KEY --role preview

project env commands target the project the directory is linked to; in CI, pass --project <id-or-name> on each command instead (Known limitations). add fails if the key already exists in that scope; use update to replace a value. --branch <name> sets an override for one preview branch, and --file .env.production imports a dotenv file instead of a single key. list shows names and metadata, never values (project command reference). Running the CLI with npx needs Node.js 22.18 or newer on the 22 line, 24.11 or newer on the 24 line, or 26 or newer.

A deploy can also seed the value: when a stage lacks the variable, the deploy copies it from the deploying shell (Deploying). So a deploy from your laptop can succeed while a fresh CI stage needs the value exported in the CI job.

Values resolve at deploy time, so deploy again after any change: run deploy, push to the default branch if deploy on push is set up, or promote a version, which rebuilds it with the production variables (Compute FAQ).

Two details matter for Next.js. deploy doesn't build for you: you run the build before deploy, locally or in CI, and deploy on push runs your build command in GitHub Actions (Known limitations). So NEXT_PUBLIC_ values come from the environment where next build ran. And pages that read runtime configuration need export const dynamic = "force-dynamic" (Compute FAQ).

Know the limits before you rely on it:

  • Values are write-only. The CLI, the API and the Console never return them, and there is no command to pull them into a local .env, so keep the source copy in a secret manager.
  • You set values with the CLI, or a deploy copies missing ones from the deploying shell. The Console lists variable names, never values.
  • Keys must match [A-Z_][A-Z0-9_]*, and each value can be up to 8 KB. A larger credential, such as a long certificate chain, needs another delivery method, such as fetching it from a secret manager at startup.
  • A changed value needs a new deployment. Prisma Compute has no documented integration that reads values from an external secret manager while the app runs.

If your app already runs on Vercel, Netlify, Render, Railway or Fly.io, moving hosts doesn't fix a missing variable. Set it where the app runs and redeploy there.

How to prevent it

Commit a .env.example that lists every variable name with a placeholder value, and update it in the same change that adds a new process.env read. Keep the startup check from step 5, so a deploy with a missing key fails in the logs with the variable's name. Store the real values in one place you control, such as a password manager or a secret manager, and copy them to each host and CI system from there.

Never log a whole process.env object or a request that includes an Authorization header. If a key ends up in a commit or a log, rotate it with the provider before you clean up: GitHub's guide puts revoking or rotating the secret first.

When this fix doesn't apply

If the variable is set and the app still gets a 401 or 403, the key arrives but is wrong: a test key in production, a revoked key, or a key from another account. Compare the key's prefix or last characters with the provider's dashboard instead of printing it.

If the missing value is DATABASE_URL and you don't have a database yet, follow the DATABASE_URL guide. For how to separate production and preview credentials, rotate them and hand them over to a contractor, see where database passwords and API keys go when you deploy.

Frequently asked questions

No. Anyone who can read the repository, its forks or its history can then use the key. Next.js's create-next-app adds .env files to .gitignore for that reason. Set the value in the host's environment settings, and keep the source copy in a password manager or secret manager. A .env.example file with names and placeholder values is the part to commit.

For one app on one host, the host's variables are usually enough, and hosts such as Vercel and Fly.io document that they encrypt stored values. You still need a copy somewhere else, because several hosts never show a value again after you save it: Vercel's Secret type, Fly.io secrets and Prisma Compute variables are all write-only. A secret manager earns its place when several apps, hosts or CI jobs share the same credentials, or when you rotate them often.

Treat it as exposed. Create a new key with the provider, put it in the host's settings, redeploy, then revoke the old key. GitHub's guide to removing sensitive data says to revoke or rotate the secret as the first step, because rewriting Git history doesn't remove copies in clones, forks or caches. A key inlined into JavaScript through NEXT_PUBLIC_ or VITE_ is readable by anyone who loads the page, so move the call that needs it to server code.

Yes, with one more step if you have no database yet: create one first, then set its connection string as DATABASE_URL on the host and redeploy. The DATABASE_URL guide walks through that case, including pooled and direct connection strings. On Prisma Compute, a database declared in the Composer module is created by the deploy and reaches the app as db.url from service.load(), so there is no DATABASE_URL to set (Databases).

Set production and preview secrets on Prisma Compute

Store each key per environment with the Prisma CLI, keep values write-only, and deploy to apply them.