Keeping Secrets Out of a Next.js App
#next.js#secrets#supabase#security
In Next.js, a secret is safe only if it never leaves the server, and it escapes in four ways: the NEXT_PUBLIC_ prefix (inlined into the browser bundle), server code that hands it to a "use client" component through an import or a prop, a hardcoded value in source, and git history. Read secrets from unprefixed env vars in server-only code, catch them with a pre-commit hook before they reach GitHub, and rotate anything that has already shipped.
Next.js blurs the line between server and client on purpose — the same repo renders on both. That's great for productivity and dangerous for secrets, because it's genuinely easy to write code that looks server-side but gets bundled and shipped to every visitor. Here are the four escape routes, worst-first, and how to close each.
1. The NEXT_PUBLIC_ prefix (the most common leak)
Any environment variable named NEXT_PUBLIC_* is inlined into the client JavaScript at build time and shipped to every browser. That's the intended behavior — it's how you expose safe public values like your site URL or the Supabase anon key. The problem is when a real secret gets that prefix, usually copy-pasted from a tutorial or added "just to make it work" — most often while chasing a missing env var through a failing deploy:
// This publishes your master key to every visitor.
process.env.NEXT_PUBLIC_SERVICE_ROLE_KEY
The Supabase service_role key bypasses all RLS, so publishing it is a full database compromise. GuardLayer flags a secret-looking NEXT_PUBLIC_ value as critical — but it deliberately stays quiet on genuinely public ones (anon keys, pk_ publishable keys, analytics tokens), because not every NEXT_PUBLIC_ var is a leak. Here's live engine output on the combined mistake — a client module reading the service_role key:
- Criticallib/supabaseAdmin.ts:7
Service role key exposed to the client
Drop the NEXT_PUBLIC_ prefix so Next.js never puts the key in the browser bundle, and read it only in server code (a Route Handler or Server Action). Rotate the key immediately since it has been exposed. - Criticallib/supabaseAdmin.ts:7
Service role key used in client-side code
Move all service-role usage into a server context (Route Handler, Server Action, or server-only module). On the client use only the anon key, protected by RLS. - Criticallib/supabaseAdmin.ts:7
Secret exposed through NEXT_PUBLIC_
Drop the NEXT_PUBLIC_ prefix and read the value only on the server. Publishable/anon keys are fine to expose; secret keys, tokens, and passwords are not — rotate any that have shipped.
The fix: drop the prefix and read it only on the server.
import "server-only";
import { createClient } from "@supabase/supabase-js";
// server-only throws at build time if this is ever imported client-side.
export const adminClient = createClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY! // no NEXT_PUBLIC_ prefix
);
2. Server code that hands a secret to a client component
Through an import
Even without a NEXT_PUBLIC_ prefix, a secret leaks the moment a "use client" component imports a module that reads it — Next.js bundles the whole dependency for the browser. The server-only package is the guardrail: import it at the top of any module that touches secrets, and an accidental client import becomes a build error instead of a silent leak. This is the single highest-leverage line you can add to a secret-holding file.
Next.js does replace a direct, unprefixed process.env.STRIPE_SECRET_KEY read in client code with an empty string, so a bare env read often blanks out instead of leaking. That protection does not cover a constant computed at module load, a value read through a dynamic key, or a hardcoded literal. Those go straight into the bundle, so treat the empty string as a fallback, not a boundary.
Through a prop
This one is specific to the App Router. When a Server Component passes props to a Client Component, the props are serialized into the RSC payload and embedded in the HTML, inside self.__next_f.push(...) script tags. Next.js's security guidance says all of a Client Component's props end up in the generated HTML, whether or not the component reads them:
// Server Component: user = { id, name, email, passwordHash, apiToken, ... }
return <ProfileCard user={user} />; // every field ships to the client
// Fix: shape the data on the server and pass only what the component needs
return <ProfileCard name={user.name} avatarUrl={user.avatarUrl} />;
3. Hardcoding the value
Pasting a literal sk_live_… or eyJ… token into source is the most direct leak, and the most permanent, because deleting the line later doesn't remove it from git history (see section 4). It usually lands in a shared SDK module like lib/stripe.ts that hardcodes the key "so every route can import it", in a route handler that inlines the key instead of reading process.env, or as the quick fix when a server-only variable reads as undefined in a Client Component. If a Client Component imports that module, the literal also ends up in the browser bundle. Keep every secret in an untracked .env.local, reference it via process.env, and make sure .env* is in .gitignore. The hardcoded Supabase JWT is the same mistake in a Supabase-shaped disguise. So is an Apple .p8 signing key pasted into a client-secret helper; Supabase's Apple Secret Key field wants a JWT instead.
4. Git history (the leak that outlives the fix)
This is the one people forget. Every state your code has ever been in is recoverable from git. A key that was committed once — even if deleted in the very next commit — is still there for anyone who can clone the repo, and bots scrape public repos for exactly this. So "I removed it" is never the whole fix.
Deleting the line creates a new snapshot. The old commit, and the blob holding the key, stays in the object database and travels with every clone, fork, and fetch. Recovering it takes two commands:
git log --all --oneline -- lib/stripe.ts # every version of the file
git show <commit>:lib/stripe.ts # the file as it was at that commit
Catch keys before they reach GitHub
Cleanup after the fact is partial at best, so the cheapest fix is stopping the key before it's pushed. There are two places to do that, and they do different jobs.
Layer 1: a local pre-commit hook. This is the only place you can block a secret before it leaves your machine. gitleaks is the common choice:
#!/bin/sh
# .git/hooks/pre-commit (or wire it via the pre-commit framework)
gitleaks git --pre-commit --staged --redact --verbose || {
echo "Secret detected in staged changes, commit blocked."
exit 1
}
The key never enters even a local commit. The catch is that hooks are per-machine and skippable with git commit --no-verify, so you can't rely on them alone.
Layer 2: a scan on every push. A repo-connected scanner runs after the code reaches GitHub, so it can't un-push a commit. GuardLayer scans every push, flags a hardcoded provider key or a secret behind NEXT_PUBLIC_ as critical, and posts a pass/fail check on the commit and PR. That check is an alert by default. To stop a failing check from merging into main, make it a required status check in your branch protection. Either way you learn a key shipped while there's still time to rotate it.
The same scan reads your workflow files, because a committed key isn't the only way a secret leaks through GitHub: a pull_request_target workflow that checks out fork pull request code and runs it hands your Actions secrets to whoever opened the PR.
How do I get a secret out of my Next.js repo after it leaked?
Deleting the line is step zero, not the fix. Do all three:
- Rotate first. Revoke the exposed key at the provider (Supabase dashboard, Stripe, etc.) and issue a new one. Assume the old one is burned — treat it as already captured.
- Move it server-side. Store the new value in
.env.local(untracked), read it via unprefixedprocess.envinside aserver-onlymodule. - Purge history. Use
git filter-repoor BFG to remove the string from every past commit, then force-push. Deleting the file in a new commit is not enough.
echo 'sk_live_51Nk2pLZvKq9rT4xBwHc8mYdQ==>REMOVED' > replacements.txt
git filter-repo --replace-text replacements.txt
# filter-repo drops the remote: re-add it, then
git push --force --all
Rewriting history changes commit hashes, so collaborators need to re-clone. Cached views on the forge and existing forks may still hold the old blob, which is why rotation comes first.
A 30-second self-check
# Any secret-looking value behind a public prefix?
grep -rn "NEXT_PUBLIC_.*\(SECRET\|SERVICE_ROLE\|PRIVATE\|TOKEN\)" .
# Any secret-shaped literal committed in source?
grep -rnE "(sk_live_|eyJ|AKIA|ghp_)" --include="*.ts" --include="*.tsx" .
# Is your built bundle carrying anything it shouldn't?
grep -rE "sk_live_|sk-|service_role" .next/static 2>/dev/null
# Is a sensitive field in the rendered HTML / RSC payload?
curl -s https://your-app.com/profile/123 | grep -o 'passwordHash\|apiToken\|service_role'
# Was a key ever committed? A clean working tree says nothing about history.
git log -p --all -S 'sk_live_' -- '*.ts' '*.js'
Any hit is work to do, and anything in .next/static has already shipped to the browser. GuardLayer runs checks like these, plus ones grep can't express such as telling a public anon key from a real secret, on every push, with the fix inline. It reads one file at a time, so it does not follow the import graph or check which fields a Client Component receives as props. server-only and a review of Client Component props still cover those.
FAQ
Which env vars are safe to prefix with NEXT_PUBLIC_?
Only values that are meant to be public: your site URL, the Supabase anon key, publishable (pk_) payment keys, and analytics tokens. Never a service_role key, a secret API key, a password, or a connection string.
Is .env.local safe by default?
Yes, as long as it's untracked. Next.js ignores .env*.local in its starter .gitignore, but confirm it — a committed .env.local puts every secret straight into history.
Does server-only actually hide the secret, or just warn?
It throws a build-time error if a client bundle tries to import the module, so the secret physically never reaches the browser. It's a hard guardrail, not a lint warning.
If a secret is only used in an API route or Server Action, am I safe?
Usually yes — those run on the server. The danger is the NEXT_PUBLIC_ prefix and accidental imports into "use client" files. Verify the variable name and that no client component imports the module.
I pass a whole user object to a Client Component but only render the name. Is that a leak? Yes, if the object has sensitive fields. All props are serialized into the HTML regardless of what the component renders. Pass only the fields it needs.
The repo is private. Am I safe? Safer, but not safe. Private repos get cloned by CI, forked internally, exposed through misconfigured access, and accidentally made public. Treat any committed secret as compromised and rotate it.
Does GuardLayer replace gitleaks?
No, they're complementary. gitleaks blocks the commit locally. GuardLayer scans every push as a server-side backstop and also flags Next.js/Supabase-specific leaks, like a NEXT_PUBLIC_ secret, that generic secret scanners don't.
See which of your Supabase tables anyone can read, free
Connect your Supabase project read-only. GuardLayer checks RLS, policies, grants and functions as they are right now, and gives you the SQL to fix each problem. It never reads your rows and can't change anything.
Check my Supabase projectPrefer to check code instead? Scan your repo, no signup.