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.


_18
// app/api/ask/route.ts
_18
import Anthropic from '@anthropic-ai/sdk';
_18
import { NextResponse } from 'next/server';
_18
_18
const client = new Anthropic(); // reads ANTHROPIC_API_KEY from the server environment
_18
_18
export async function POST(req: Request) {
_18
const { prompt } = await req.json();
_18
_18
const response = await client.messages.create({
_18
model: 'claude-haiku-5-5',
_18
max_tokens: 512,
_18
messages: [{ role: 'user', content: String(prompt).slice(0, 2000) }],
_18
});
_18
_18
const text = response.content.map((b) => (b.type === 'text' ? b.text : '')).join('');
_18
return NextResponse.json({ text });
_18
}

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.


_10
# .env.local
_10
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.


_10
const res = await fetch('/api/ask', {
_10
method: 'POST',
_10
headers: { 'Content-Type': 'application/json' },
_10
body: JSON.stringify({ prompt }),
_10
});
_10
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.


_13
'use server';
_13
import Anthropic from '@anthropic-ai/sdk';
_13
_13
const client = new Anthropic();
_13
_13
export async function ask(prompt: string) {
_13
const response = await client.messages.create({
_13
model: 'claude-haiku-5-5',
_13
max_tokens: 512,
_13
messages: [{ role: 'user', content: prompt.slice(0, 2000) }],
_13
});
_13
return response.content.map((b) => (b.type === 'text' ? b.text : '')).join('');
_13
}

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.


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

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.


_10
const limit = await rateLimiter.check(`ask:${user.id}`, { max: 20, windowSeconds: 60 });
_10
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.
#

quick question

Was this resource helpful?