NEXT_PUBLIC_ Leaked Your API Key: The Next.js / Vercel Bundle Trap
In Next.js, any env var prefixed NEXT_PUBLIC_ is baked into the JavaScript your visitors download. Here's how secret keys leak this way, how to find them, and how to fix it.
· 5 min read
Here's a trap that catches a lot of Next.js apps — especially ones an AI tool scaffolded: any environment variable prefixed with NEXT_PUBLIC_ is inlined into the JavaScript bundle sent to every visitor's browser. Not hidden on the server — literally in the code anyone can read with View Source or DevTools.
Quick test
Ctrl/Cmd-F in DevTools → Sources, and search the bundle for sk-, sk_live, or service_role. If anything shows up, it's already public.Why this happens
The NEXT_PUBLIC_ prefix is a feature — it's how you expose genuinely public config (a public API URL, an analytics project ID) to the browser. The problem is that AI tools and copy-paste tutorials slap it on secret keys too, so the thing that's supposed to stay private ships to the world at build time.
Which keys are safe as NEXT_PUBLIC_ — and which are not
- Safe (designed to be public): Stripe publishable key (
pk_live_…), Supabaseanonkey, PostHog project key. - Never public: anything secret — Stripe
sk_live_…, OpenAIsk-…, Anthropicsk-ant-…, Supabase service-role key, or any server-side API secret.
How to fix it
- Rotate the leaked key first — it's in the bundle history and CDN caches; assume it's compromised.
- Move the secret server-side. Drop the
NEXT_PUBLIC_prefix and call the service from a Route Handler or Server Action, so the key stays on the server and only the result reaches the browser. - Keep only truly-public values as
NEXT_PUBLIC_.
Find keys leaking in your live bundle — free
Trust scans the shipped JavaScript of your URL and your repo for exposed secrets.
Run a free scan →A repo grep only catches what's in source. Trust also scans your live site— the actual JavaScript your users download — so it catches keys that made it all the way into production, then tells you exactly which file and how to fix it.