---
title: "How do I keep my AI API key out of the browser?"
description: "Anything shipped to the browser is public, NEXT_PUBLIC_ included. Call the model from a Route Handler or server action and keep the key in a server-only env var."
url: https://www.danny.engineering/answer/ai/how-do-i-keep-my-ai-api-key-out-of-the-browser
author: Danny
published: 2026-12-03T00:00:00.000Z
updated: 2026-12-03T15:34:00.000Z
tags: ["AI"]
---

# How do I keep my AI API key out of the browser?

## The short answer


Never call the model's API from client-side JavaScript. Put the key in a server-only environment variable, write a small Route Handler (or server action) that makes the call, and have the browser talk to that instead. Then protect that endpoint with authentication and rate limiting, because an open proxy is only slightly better than a leaked key: anyone who finds it can run up your bill.


```typescript
// app/api/ask/route.ts
import Anthropic from '@anthropic-ai/sdk';
import { NextResponse } from 'next/server';

const client = new Anthropic(); // reads ANTHROPIC_API_KEY from the server environment

export async function POST(req: Request) {
  const { prompt } = await req.json();

  const response = await client.messages.create({
    model: 'claude-haiku-5-5',
    max_tokens: 512,
    messages: [{ role: 'user', content: String(prompt).slice(0, 2000) }],
  });

  const text = response.content.map((b) => (b.type === 'text' ? b.text : '')).join('');
  return NextResponse.json({ text });
}
```


## What it means


Everything the browser can read, the user can read. Your JavaScript bundle, your network requests, your request headers: all of it is a right-click away in DevTools. If the key is anywhere in that bundle, or sent in an `Authorization` header from the browser, it is public. Obfuscation does not help; someone will find the string that starts with `sk-` in under a minute.


In Next.js, environment variables are server-only by default. `process.env.ANTHROPIC_API_KEY` is `undefined` in client code, which is exactly what you want. The `NEXT_PUBLIC_` prefix is the opt-out: it tells the bundler to inline the value into the client JavaScript at build time. The name is a warning, not a convenience. If you ever find yourself writing `NEXT_PUBLIC_ANTHROPIC_API_KEY`, stop, because you are about to publish your key to everyone who loads the page.


The fix is a proxy: a server endpoint that you control, that holds the key, and that makes the real request on the user's behalf. The browser never sees the key, and you get a place to add checks before each call.


## How to do it


### Keep the key in a server-only variable


Put the key in `.env.local`, which the default Next.js `.gitignore` excludes from the repository.


```bash
# .env.local
ANTHROPIC_API_KEY=sk-ant-...
```


In production, set it in your host's environment variable settings rather than in a file. The SDK reads it automatically when you call `new Anthropic()` in server code. Do not import the SDK in any file marked `'use client'`; the bundler will try to include it, and the key will be missing anyway.


### Proxy through a Route Handler


The Route Handler in the short answer is the whole pattern. The browser sends a prompt to `/api/ask`, the server adds the key, calls the API, and returns the text. Call it from the client like any other endpoint.


```typescript
const res = await fetch('/api/ask', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ prompt }),
});
const { text } = await res.json();
```


### Or use a server action


If the call is triggered by a form or button in a React component, a server action removes the fetch boilerplate. Server actions run on the server, so the key is safe here too.


```typescript
'use server';
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic();

export async function ask(prompt: string) {
  const response = await client.messages.create({
    model: 'claude-haiku-5-5',
    max_tokens: 512,
    messages: [{ role: 'user', content: prompt.slice(0, 2000) }],
  });
  return response.content.map((b) => (b.type === 'text' ? b.text : '')).join('');
}
```


Remember that a server action is still a public HTTP endpoint. Anyone can call it with any input. The same authentication and rate-limiting rules apply.


### Add authentication


An unauthenticated proxy is a free API key for whoever finds the URL. At minimum, require a signed-in user and reject everyone else before you touch the model. Use whatever session mechanism your app already has.


```typescript
export async function POST(req: Request) {
  const user = await getCurrentUser(req); // your auth helper
  if (!user) return new Response('Unauthorised', { status: 401 });
  // ... make the call
}
```


If the feature has to work for anonymous visitors, you still need something: a signed, short-lived token issued by your own server, a CAPTCHA before the first request, or at least a strict per-IP limit.


### Add rate limiting


Even logged-in users can loop a request a thousand times. Limit each user (or IP) to a sensible number of calls per minute. On a single long-running server an in-memory counter works; on serverless hosts, where each request may land on a different instance, use a shared store such as Redis or your database.


```typescript
const limit = await rateLimiter.check(`ask:${user.id}`, { max: 20, windowSeconds: 60 });
if (!limit.ok) return new Response('Too many requests', { status: 429 });
```


Also cap the input. `prompt.slice(0, 2000)` in the examples stops someone pasting a novel and charging you for it. Choose a cheaper model (`claude-haiku-5-5`) for public-facing features and a conservative `max_tokens`.


### Never log the key, and set a spend limit


Do not log request headers or the SDK client object, and do not print `process.env` in a debugging session. Error reporting tools often capture local variables; make sure the key is not among them. In your provider's console, set a monthly spend limit and a usage alert so a leak or a bug costs a fixed amount rather than an open-ended one.


### If a key leaks, rotate it


If a key has been in a client bundle, in a public repository, in a screenshot, or in a commit you later removed, treat it as leaked. Git history counts. Go to the provider console, create a new key, update your server environment, deploy, then delete the old key. Do this first and investigate afterwards.


## Common pitfalls

- **Using** **`NEXT_PUBLIC_`** **to "make it work".** The error "key is undefined" in client code is Next.js protecting you. The fix is to move the call to the server, not to expose the variable.
- **Shipping a proxy with no auth.** Bots scan for endpoints that return model output. An open `/api/chat` will be found and used.
- **Committing** **`.env`** **files.** `.env.local` is ignored by default, but `.env` and `.env.production` may not be. Check `.gitignore` before your first commit.
- **Forwarding the user's prompt unchanged.** Cap its length, and consider stripping anything that is clearly not a question. You are paying per token.
- **Logging full request objects.** A debug log of "everything about this request" is where keys usually end up. Log the fields you need and nothing else.
- **Assuming a removed commit is gone.** Deleting the key from the working tree does not delete it from history or from the forks and mirrors that already pulled it. Rotate.

## Related reading

- [Environment variables in Next.js](https://nextjs.org/docs/app/guides/environment-variables)
- [Route Handlers in Next.js](https://nextjs.org/docs/app/api-reference/file-conventions/route)
- [Server Functions in the React docs](https://react.dev/reference/rsc/server-functions)
- [OWASP API Security Project](https://owasp.org/www-project-api-security/)
