CORS & Preflight Simulator · Next.js Route Handlers + External SPA / Widget

Next.js Route Handlers + External Frontend CORS Simulator & Fix Guide

Simulate Fetch Standard preflight (OPTIONS) triggers, credential rules, and origin matching between External SPA / Widget and Next.js Route Handlers. Copy generated configuration code below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Browser Request (External SPA / Widget)

2. Server Response Policy (Next.js Route Handlers)

Access-Control-Allow-Methods
// next.config.ts — Static CORS Headers for Next.js Route Handlers
import 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;

Preflight (OPTIONS)

Triggered · Passed

Content-Type "application/json" is not CORS-safelisted (only application/x-www-form-urlencoded, multipart/form-data, and text/plain avoid preflight). Request includes non-safelisted header(s): Authorization.

Browser Verdict

Allowed

Browser CORS validation passed. JavaScript can read the response body.

Rule Engine Diagnostics

  • Reverse Proxy Tip: Avoid Duplicate CORS Headers in Nginx + Upstream App

    Never configure Access-Control-Allow-Origin in both Nginx and your backend framework simultaneously. Browsers reject duplicate headers with: "The 'Access-Control-Allow-Origin' header contains multiple values '*, https://client.example.com', but only one is allowed." Choose one layer (or use proxy_hide_header in Nginx).

Simulated HTTP Response Headers

HTTP/1.1
Preflight (OPTIONS)
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://client.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Actual Response (POST)
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://client.example.com
Vary: Origin

Runs locally in your browser. Origins, endpoints, and headers are never sent to a server.

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:

DevTools Console Output

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.

  1. 1Add Static CORS Headers for Single-Origin APIs in next.config.ts

    next.config.ts

    For 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.tstypescript
    import 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;
  2. 2Export an Explicit OPTIONS Handler in Your Route Handler

    src/app/api/public/checkout/route.ts

    Next.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.tstypescript
    import { 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) }
      );
    }
  3. 3Centralize Multi-Origin Preflights in Next.js Middleware

    src/middleware.ts

    When 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.tstypescript
    import { 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*',
    };
  4. 4Verify Single-Layer Headers and Prevent next.config.ts Collisions

    verification checklist

    Choose 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.

Pitfall 1

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.

Pitfall 2

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."

Pitfall 3

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.

Related Tool · Same-Origin Reverse 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).

Open Nginx Builder

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.
Browse all 12 stacks →