5 min read · Updated June 10, 2026
How to Secure API Keys in a Next.js AI App
To secure API keys in a Next.js AI app, keep every provider secret in a non-public environment variable and call the AI provider only from server-side code such as Route Handlers or Server Actions. The browser should send an authenticated request to your own endpoint, which validates the user, applies rate limits, calls the provider, and returns only the required response. Never prefix a secret with NEXT_PUBLIC_, because Next.js inlines those values into JavaScript delivered to the browser.
Why are client-side AI API keys unsafe?
Anything delivered to a browser must be treated as public. A user can inspect JavaScript bundles, network requests, browser storage, and runtime state. Obfuscation does not turn a client-side secret into a protected credential.
Next.js documents that non-NEXT_PUBLIC_ environment variables remain server-side, while NEXT_PUBLIC_ variables are bundled into browser JavaScript. AI provider keys therefore belong only in server-side environment variables.
What should the secure request flow look like?
A secure request starts in the browser but terminates at your own protected server endpoint. That endpoint should authenticate the user, validate and constrain the input, enforce a per-user or per-IP usage limit, call the AI provider with the server-side key, and return a controlled response.
- Store provider secrets in server-only environment variables.
- Use a Route Handler or Server Action as the provider proxy.
- Authenticate before spending provider credits.
- Validate input length, type, and allowed model options.
- Apply rate limits and log abnormal usage.
- Return safe error messages without exposing provider details.
What mistakes still expose AI credentials?
Common failures include adding a secret to a NEXT_PUBLIC_ variable, calling the provider directly from a Client Component, committing an .env file, returning verbose provider errors, and protecting an endpoint without rate limiting. Security requires both secret isolation and abuse controls.