Next.jsMedium
What is CORS and how do you configure it in Next.js?
CORS (Cross-Origin Resource Sharing) is the browser mechanism that decides whether JavaScript on one origin may read responses from another origin. The server opts in with Access-Control-Allow-* headers. In Next.js you set them in a Route Handler (including an OPTIONS handler for preflights), in proxy.ts, or with headers() in next.config.ts.
How it works
- Simple requests (GET/POST with basic headers) are sent; the browser blocks reading the response unless
Access-Control-Allow-Originmatches. - Preflighted requests (custom headers like
Authorization, JSONContent-Type, PUT/DELETE) first sendOPTIONS. The server must answer with allowed origin, methods and headers. - Credentials (cookies) require
Access-Control-Allow-Credentials: trueand an explicit origin, never*.
Options in Next.js
- Per Route Handler: add headers to responses and export
OPTIONS. proxy.ts: one place for all/api/*routes, checking theOriginagainst an allowlist and answering preflights.next.config.tsheaders(): static headers for a path pattern. Simple, but it cannot vary by origin.
Security notes
- CORS only restricts browsers. It does not protect an API from curl or servers; you still need authentication.
- Reflecting any
Originback with credentials enabled is a vulnerability. Use an allowlist. - Add
Vary: Originwhen the header changes per origin, so caches do not mix responses. - Same-origin calls (your own Next.js frontend) do not need CORS at all.
Code example
tsx
1// app/api/public/data/route.ts2const ALLOWED = new Set(["https://app.acme.com", "https://partner.example.com"]);34function corsHeaders(origin: string | null) {5 const headers: Record<string, string> = {6 "Access-Control-Allow-Methods": "GET, POST, OPTIONS",7 "Access-Control-Allow-Headers": "Content-Type, Authorization",8 "Access-Control-Max-Age": "86400",9 Vary: "Origin",10 };11 if (origin && ALLOWED.has(origin)) headers["Access-Control-Allow-Origin"] = origin;12 return headers;13}1415export function OPTIONS(request: Request) {16 return new Response(null, { status: 204, headers: corsHeaders(request.headers.get("origin")) });17}1819export async function GET(request: Request) {20 const data = { items: [1, 2, 3] };21 return Response.json(data, { headers: corsHeaders(request.headers.get("origin")) });22}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.