Typical Browser Console Error (External SPA / Widget → Next.js Route Handlers)
When cross-origin headers are missing, mismatched, or blocked during preflight between External SPA / Widget and Next.js Route Handlers, Chrome and Firefox log an error matching the pattern below in DevTools:
Access to fetch at 'https://api.myapp.com/api/public/checkout' from origin 'https://client.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Why CORS Blocks Requests Between External SPA / Widget and Next.js Route Handlers
When you expose Next.js App Router Route Handlers (app/api/**/route.ts) to external browser clients; such as an embeddable checkout widget, a separate marketing domain, a browser extension, or an independent Vite SPA; Next.js does not automatically answer HTTP OPTIONS preflight requests. Even after configuring Access-Control-Allow-Origin inside next.config.ts, hitting a Route Handler that only exports POST can still fail preflight with HTTP 405 Method Not Allowed.
Under the WHATWG Fetch Standard, a CORS preflight response MUST return an HTTP 2xx status code (typically 204 No Content or 200 OK). If Next.js responds with 405 Method Not Allowed because no OPTIONS handler was exported in route.ts (or intercepted inside src/middleware.ts), Chrome and Firefox abort the request immediately with "It does not have HTTP ok status" regardless of whether next.config.ts attached valid Access-Control-Allow-Origin headers.
Static headers in next.config.ts work cleanly when only one fixed external origin (or public wildcard * without credentials) consumes your Route Handlers. However, as soon as you need to authorize multiple whitelisted customer origins dynamically across staging and production, static config headers cannot inspect the incoming Origin header; you must evaluate CORS dynamically in Next.js middleware.ts or inside a shared Route Handler utility while always returning Vary: Origin.
Because Next.js Route Handlers often run across distributed serverless functions or Edge Runtime isolates, verifying CORS behavior across both cold starts and cached CDN responses is essential before onboarding external widget customers or third-party SPAs. Confirm that every external endpoint either exports an explicit OPTIONS handler or is covered by a strict src/middleware.ts matcher returning 204 No Content. Inspect response headers in production with curl to ensure Vary: Origin is present, duplicate Access-Control-Allow-Origin headers are never emitted by combining next.config.ts with route-level headers, and unauthorized origins cleanly receive zero CORS allow headers.
Step-by-Step Next.js Route Handlers + External SPA / Widget CORS Fix Guide
Follow each step below in order to eliminate preflight failures and lock down production origins safely for Next.js Route Handlers.
1Add Static CORS Headers for Single-Origin APIs in next.config.ts
next.config.tsFor a single external origin, declare async headers() in next.config.ts targeting /api/:path*. Always pair an explicit origin with Vary: Origin so Vercel, Cloudflare, or Fastly edge caches never leak one origin's Access-Control-Allow-Origin header to another domain.
next.config.tstypescriptimport type { NextConfig } from 'next'; const nextConfig: NextConfig = { async headers() { return [ { source: '/api/:path*', headers: [ { key: 'Access-Control-Allow-Origin', value: 'https://client.example.com' }, { key: 'Access-Control-Allow-Methods', value: 'GET, POST, PUT, DELETE, OPTIONS' }, { key: 'Access-Control-Allow-Headers', value: 'Content-Type, Authorization' }, { key: 'Access-Control-Max-Age', value: '86400' }, { key: 'Vary', value: 'Origin' }, ], }, ]; }, }; export default nextConfig;2Export an Explicit OPTIONS Handler in Your Route Handler
src/app/api/public/checkout/route.tsNext.js App Router automatically returns 405 Method Not Allowed for OPTIONS unless you export an OPTIONS function or intercept OPTIONS in middleware.ts. Returning a 204 No Content response guarantees preflights receive a valid 2xx status with matching CORS headers.
src/app/api/public/checkout/route.tstypescriptimport { NextRequest, NextResponse } from 'next/server'; const ALLOWED_ORIGINS = new Set(['https://client.example.com']); function buildCorsHeaders(origin: string | null): HeadersInit { const headers: Record<string, string> = { 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', 'Access-Control-Max-Age': '86400', Vary: 'Origin', }; if (origin && ALLOWED_ORIGINS.has(origin)) { headers['Access-Control-Allow-Origin'] = origin; } return headers; } export async function OPTIONS(request: NextRequest) { const origin = request.headers.get('origin'); return new NextResponse(null, { status: 204, headers: buildCorsHeaders(origin) }); } export async function POST(request: NextRequest) { const origin = request.headers.get('origin'); const body = await request.json(); return NextResponse.json( { ok: true, received: body }, { status: 200, headers: buildCorsHeaders(origin) } ); }3Centralize Multi-Origin Preflights in Next.js Middleware
src/middleware.tsWhen you maintain dozens of external API Route Handlers, duplicating OPTIONS functions in every file quickly drifts out of sync. Intercept /api/:path* inside src/middleware.ts to validate the incoming Origin against a strict allowlist and answer OPTIONS preflights globally in one place.
src/middleware.tstypescriptimport { NextRequest, NextResponse } from 'next/server'; const ALLOWED_ORIGINS = new Set([ 'https://client.example.com', 'http://localhost:5173', ]); export function middleware(request: NextRequest) { const origin = request.headers.get('origin'); const isAllowed = origin ? ALLOWED_ORIGINS.has(origin) : false; if (request.method === 'OPTIONS') { const preflight = new NextResponse(null, { status: 204 }); if (isAllowed && origin) { preflight.headers.set('Access-Control-Allow-Origin', origin); } preflight.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); preflight.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization'); preflight.headers.set('Access-Control-Max-Age', '86400'); preflight.headers.set('Vary', 'Origin'); return preflight; } const response = NextResponse.next(); if (isAllowed && origin) { response.headers.set('Access-Control-Allow-Origin', origin); response.headers.set('Vary', 'Origin'); } return response; } export const config = { matcher: '/api/:path*', };4Verify Single-Layer Headers and Prevent next.config.ts Collisions
verification checklistChoose either static headers in next.config.ts (single origin) OR dynamic headers in middleware.ts / route.ts (multiple origins). Setting Access-Control-Allow-Origin in both places can emit comma-joined duplicate values that browsers immediately reject. Confirm the exact headers over curl before shipping.
verification checklistbash# Verify a single Access-Control-Allow-Origin header is returned: curl -i -X OPTIONS https://api.myapp.com/api/public/checkout \ -H "Origin: https://client.example.com" \ -H "Access-Control-Request-Method: POST" \ -H "Access-Control-Request-Headers: content-type, authorization"
Common Next.js Route Handlers + External SPA / Widget CORS Pitfalls
Even when your basic origin string looks correct, these three framework-specific edge cases frequently reintroduce CORS failures in staging and production environments.
405 Method Not Allowed on OPTIONS Breaking Preflights
Adding CORS headers solely in next.config.ts without exporting an OPTIONS handler or intercepting OPTIONS in middleware.ts causes App Router endpoints to return HTTP 405. Browsers reject any non-2xx preflight response regardless of headers.
Duplicate Access-Control-Allow-Origin From next.config.ts + Route Handler
Setting Access-Control-Allow-Origin in both next.config.ts and NextResponse.json() causes Next.js or the hosting edge network to emit comma-joined duplicate values, triggering the browser error "contains multiple values, but only one is allowed."
Vercel Deployment Protection Redirecting Unauthenticated Preflights
On preview deployments where Vercel Authentication is enabled, OPTIONS preflight requests get redirected (302/401) to Vercel's login screen because browsers omit cookies on non-credentialed preflights. Bypass protection for API routes or test on an unprotected preview domain.
Deploying Behind Nginx? Eliminate CORS Preflights or Configure Your Proxy
Configure TLS, WebSocket headers, and X-Forwarded-Proto, or serve your frontend and /api/ on the same origin with Nginx Reverse Proxy Config for Next.js SSR (App Router, SSL & Streaming).
Frequently Asked Questions
- Can next.config.ts async headers() allow multiple specific origins?
- No. The HTTP Access-Control-Allow-Origin header only permits a single origin string or wildcard *. Because next.config.ts headers are evaluated statically, supporting multiple dynamic origins requires inspecting request.headers.get("origin") inside src/middleware.ts or your Route Handlers.
- Why does Chrome say "It does not have HTTP ok status" for my Next.js API route?
- That exact Chrome error indicates the OPTIONS preflight request returned a non-2xx status code; most commonly 405 Method Not Allowed (missing OPTIONS export), 401 Unauthorized (auth middleware blocked OPTIONS), or 308 Permanent Redirect (trailingSlash mismatch).
- Does Next.js trailingSlash: true affect CORS preflights?
- Yes. If next.config.ts sets trailingSlash: true and an external client fetches /api/public/checkout without a trailing slash, Next.js issues a 308 redirect on the OPTIONS preflight, which browsers strictly forbid. Always call the canonical URL matching your trailingSlash setting.
- Should I use Next.js Middleware or per-route helpers for CORS?
- Use src/middleware.ts with matcher: "/api/:path*" when your external API shares consistent CORS rules across many endpoints, and use a small helper function inside route.ts when individual endpoints require distinct origin policies, credentials, or webhook exemptions.
Related CORS Stack Simulators
Browse all 12 stacks →Node.js Express + Next.js App Router CORS Simulator & Fix Guide
Fix CORS preflight and cookie credential errors between Node.js Express APIs and Next.js App Router. Configure cors() middleware, app.options, and Helmet.
FastAPI + Next.js CORS Config Simulator & Fix Guide
Fix CORS preflight failures between Python FastAPI (Uvicorn) and Next.js on port 3000. Configure CORSMiddleware order, trailing redirects, and credentials.
Cloudflare Workers API + SPA Frontend CORS Simulator & Fix Guide
Fix CORS preflight failures between Cloudflare Workers APIs and static SPAs on Pages, Vercel, or Netlify. Handle OPTIONS 204, immutable headers, and Vary.
Laravel API + Next.js App Router CORS Simulator & Fix Guide
Debug CORS between Laravel 11/12 APIs and Next.js App Router on port 3000. Separate Server Component fetches from Client Component browser preflights.