In this categoryTroubleshooting ยท 27
- How to Fix an OpenAI 401 'Invalid API Key' ErrorStart
- How to Fix OpenAI 429 Rate Limit Errors With Backoff
- How to Fix Anthropic Claude API 401 Authentication Errors
- How to Fix Google Gemini 'API Key Not Valid' Errors
- How to Fix an API Key That Loads as Undefined
- How to Handle Anthropic 529 'Overloaded' Errors
- How to Fix Rate Limit Errors from an AI API
- How to Fix CORS Errors When Calling an AI API From the Browser
- How to Fix 'Model Not Found' and Deprecated Model Errors
- How to Rotate a Leaked API Key Without Downtime
- How to Fix SSL Certificate Errors When Calling AI APIs
- How to count tokens before sending a prompt to Claude
- How to Fix 'Context Length Exceeded' Token Limit Errors
- How to fix a context length exceeded error in the Claude API
- How to fix a Claude response that gets cut off mid-sentence
- How to reduce Claude hallucinations by grounding answers in your documents
- How to keep a long Claude conversation under the context limit
- How to stop Claude from calling tools when it should not
- How to handle a Claude Fable 5 refusal with a fallback model
- How to choose the right Claude model for cost and quality
- How to cut Claude API costs with prompt caching
- How to halve Claude costs for bulk jobs with the Batch API
- How to cap spend on a Claude agent with a task budget
- How to Debug an MCP Server That Will Not Connect
- How to Ask an Agent to Explain a Bug Before Fixing It
- How to Roll Back a Bad Deploy Quickly
- How to Fix Cursor Not Indexing Your Codebase
How to Fix CORS Errors When Calling an AI API From the Browser
Stop CORS failures and protect your key by routing AI API calls through a small backend proxy.
When you call an AI provider directly from front-end JavaScript, the browser often blocks it with a CORS error, and even if it worked it would leak your secret key to every visitor. The correct fix solves both problems at once: call your own backend, and have the backend call the provider with the key kept server side.
- A front-end app making fetch calls
- A small server you control (Node, a serverless function, or similar)
- Your provider API key stored as a server secret
Step 1: Read the console error
The browser console spells out the block. It refuses the response because the provider does not send an Access-Control-Allow-Origin header for your site. You cannot add that header to someone else's server, which is why a proxy is the answer.
Step 2: Add a backend route that holds the key
Create one server endpoint that accepts the prompt from your front end, calls the provider with the secret key, and returns the result. This endpoint has the same origin as your app, so the browser is happy.
import express from "express";
import OpenAI from "openai";
const app = express();
app.use(express.json());
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
app.post("/api/chat", async (req, res) => {
const out = await client.chat.completions.create({
model: "gpt-4o-mini",
messages: req.body.messages,
});
res.json(out);
});
app.listen(3001);Step 3: Point the front end at your route
Change the front-end fetch to hit your own /api/chat path instead of the provider URL. No key, no provider domain, no CORS block.
const res = await fetch("/api/chat", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ messages }),
});
const data = await res.json();Step 4: Verify the request stays same origin
Open the network tab and confirm the call goes to your domain and returns a 200. The provider call now happens server to server, where CORS does not apply.
Result
The CORS error disappears, the key never leaves the server, and the front end talks only to your own API. This is the standard pattern every production AI app uses.
Watch related tutorials
35:00
05:00
28:00
1:42:18
28:14
41:09New guides in your inbox
Fresh step-by-step how-to guides as we publish them. One email a week, no more.