1. Guides
  2. Keeping API keys out of your app

Security

Keeping API keys out of your app

Where secret keys belong, how they leak, and three settings that help catch mistakes.

Sourced from vendor docs
Checked
20 Oct 2026
Read
2 min
Sources
4
How we check

An API key is a password for a service you pay for. If it ends up in your app's browser code or in a public repository, anyone can find it and run up your bill, or read your data. AI tools write code quickly, which makes a stray key easy to miss.

Rule one: secret keys live on the server

Code that runs in the browser can be read by anyone who visits. So any key that costs money or unlocks data (an AI provider key, a Stripe secret key, a Supabase secret key) must only be used in server code: an API route, a server function or a backend.

In Next.js, environment variables are server-only by default. Prefix one with NEXT_PUBLIC_ and Next.js copies its value into the JavaScript it sends to the browser, at build time. That's right for something public like an analytics ID, and wrong for anything secret. If a secret has that prefix, treat it as leaked.

Rule two: keep .env files out of Git

Keys usually live in a .env file on your computer. The default Next.js template adds .env files to .gitignore, so they aren't committed. Check that your project still does, especially if an AI tool created it.

Three settings that help

  1. Store keys as Secrets on your host. On Vercel, choose the Secret type when you add an environment variable. Long Secret values are redacted if they show up in build logs. Whether a Secret can be read back after you save it is unknown: we couldn't confirm it on Vercel's docs page.
  2. Turn on GitHub secret scanning. It runs automatically and free on public repositories. Private repositories in an organisation need GitHub Secret Protection.
  3. Keep push protection on. GitHub's push protection for your account is on by default and stops you pushing secrets to public repositories. Repository-level push protection is off by default and needs Secret Protection.

If a key leaks

Assume it's been copied. Create a new key with the provider, update it on your host, redeploy, then delete the old key. Removing the key from your code isn't enough, because it stays in your Git history.

Sources