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-Origin matches.
  • Preflighted requests (custom headers like Authorization, JSON Content-Type, PUT/DELETE) first send OPTIONS. The server must answer with allowed origin, methods and headers.
  • Credentials (cookies) require Access-Control-Allow-Credentials: true and an explicit origin, never *.

Options in Next.js

  1. Per Route Handler: add headers to responses and export OPTIONS.
  2. proxy.ts: one place for all /api/* routes, checking the Origin against an allowlist and answering preflights.
  3. next.config.ts headers(): 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 Origin back with credentials enabled is a vulnerability. Use an allowlist.
  • Add Vary: Origin when 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.ts
2const ALLOWED = new Set(["https://app.acme.com", "https://partner.example.com"]);
3
4function 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}
14
15export function OPTIONS(request: Request) {
16 return new Response(null, { status: 204, headers: corsHeaders(request.headers.get("origin")) });
17}
18
19export 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.

Open in study app