Cursor·Fix

Fix: CORS Errors When Calling APIs

Quick Answer

For Next.js API routes, add CORS headers in your route handler: response.headers.set('Access-Control-Allow-Origin', '*'). For external APIs, use a server-side proxy route instead of calling from the client.

Symptoms

  • !Console shows 'Access-Control-Allow-Origin' error
  • !API calls work in Postman but fail in browser
  • !Preflight OPTIONS request fails
  • !Credentials not being sent with requests

Step-by-Step Fix

1

Understand why CORS exists

CORS is a browser security feature that blocks requests from one domain to another. It only affects browser requests, not server-to-server calls.

2

Use server-side API routes

Instead of calling external APIs from client code, create a Next.js API route that proxies the request. Client → your API route → external API.

3

Add CORS headers to your API

In your API route, add headers: Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers.

4

Handle preflight requests

Browsers send an OPTIONS request before the actual request. Handle it: if (req.method === 'OPTIONS') return new Response(null, { headers: corsHeaders });

5

Configure credentials properly

If sending cookies/auth, set Access-Control-Allow-Credentials: true and specify the exact origin (not '*').

Frequently Asked Questions

No, CORS is enforced by the browser. You can't disable it. Use server-side proxying or proper CORS headers instead.

Postman doesn't enforce CORS — it's a browser-only security feature. The API itself is fine; the browser is blocking the response.

Related

Weekly Newsletter

Get next week's fix before you need it.

Join developers getting weekly vibe coding tips, error fixes, and tool updates.

Subscribe on Substack →