Full-Stack React · Route Handlers + Middleware

Next.js App Router & next.config.mjs Multi-Origin CORS Configuration

Implement dynamic multi-origin CORS with Vary: Origin in Next.js App Router route handlers and middleware.ts without the single-origin limitation of static next.config.mjs headers().

Zero Telemetry · Strict CSP (connect-src 'none')

CORS Policy & Preflight Controls

Access-Control-Allow-Methods
Simulate Browser Preflight Request (OPTIONS)
CORS Security & Fetch Spec Linter
100 / 100
PASS

Pass: 3 · Warnings: 0 · Errors: 0

CORS-002: Strict origin allowlist (2 origins) PASS
https://app.example.com, https://studio.example.com
CORS-004: Vary: Origin cache safety enabled PASS
Prevents CDN/proxy cache poisoning across distinct allowed origins.
CORS-005: Access-Control-Max-Age (7200s) within Chromium 7200s cap PASS
Avoids unnecessary OPTIONS preflight round-trips while honoring cross-browser cache ceilings.
Simulated Preflight Response
# Simulated Browser Preflight: OPTIONS /api/v1/resource
# Request Origin: https://app.example.com | Method: POST | Headers: Authorization, Content-Type
# Browser Verdict: ALLOWED (HTTP 204 No Content)

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: Authorization, Content-Type, X-Requested-With, Idempotency-Key
Access-Control-Expose-Headers: X-Request-Id, X-RateLimit-Remaining
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 7200
Vary: Origin

Copy-Paste Runtime Configs (6 Stacks)

Next.js (route.ts)
// app/api/v1/[...route]/route.ts (Next.js App Router dynamic allowlist)
import { NextRequest, NextResponse } from "next/server";

const ALLOWED_ORIGINS = new Set(["https://app.example.com","https://studio.example.com"]);

function corsHeaders(req: NextRequest): HeadersInit {
  const origin = req.headers.get("origin") ?? "";
  const allowOrigin = ALLOWED_ORIGINS.has(origin) ? origin : "";
  return {
    ...(allowOrigin ? { "Access-Control-Allow-Origin": allowOrigin } : {}),
    "Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
    "Access-Control-Allow-Headers": "Authorization, Content-Type, X-Requested-With, Idempotency-Key",
    "Access-Control-Allow-Credentials": "true",
    "Access-Control-Max-Age": "7200",
    Vary: "Origin"
  };
}

export function OPTIONS(req: NextRequest) {
  return new NextResponse(null, { status: 204, headers: corsHeaders(req) });
}
Live API & Edge Audit Zero-Upload SpecDiff

Harden your live domain headers, OpenAPI schemas & AEO discovery

Test your deployed domain's security headers, HSTS, CSP & DMARC live on ReadyCheck, diff OpenAPI contracts & OWASP API Top 10 risks in SpecDiff, or deploy all 9 production configs in minutes with the $49 ReadyCheck Fix Pack.

Protocol Rules & Header Reference

Rule / Header Production Value Behavior & Gotchas
next.config.mjs headers() Static single value only Cannot dynamically switch Access-Control-Allow-Origin across >1 allowed domain
App Router OPTIONS() export function OPTIONS(req) Required in route.ts so browser preflights return 204 instead of 405 Method Not Allowed
middleware.ts Global /api/* CORS wrapper Applies consistent allowlist + Vary: Origin across all Route Handlers
Webhook Raw Body await req.text() / req.arrayBuffer() Never call await req.json() before verifying Stripe/Creem/GitHub HMAC

Next.js middleware.ts — Dynamic Allowlist CORS for /api/*

middleware.ts
import { NextRequest, NextResponse } from "next/server";

const ALLOWED_ORIGINS = new Set([
  "https://app.example.com",
  "https://studio.example.com",
]);

export function middleware(req: NextRequest) {
  const origin = req.headers.get("origin") ?? "";
  const isAllowed = ALLOWED_ORIGINS.has(origin);

  if (req.method === "OPTIONS") {
    return new NextResponse(null, {
      status: 204,
      headers: {
        ...(isAllowed ? { "Access-Control-Allow-Origin": origin } : {}),
        "Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
        "Access-Control-Allow-Headers": "Authorization, Content-Type, Idempotency-Key",
        "Access-Control-Allow-Credentials": "true",
        "Access-Control-Max-Age": "7200",
        Vary: "Origin",
      },
    });
  }

  const res = NextResponse.next();
  if (isAllowed) {
    res.headers.set("Access-Control-Allow-Origin", origin);
    res.headers.set("Access-Control-Allow-Credentials", "true");
  }
  res.headers.set("Vary", "Origin");
  return res;
}

export const config = { matcher: ["/api/:path*"] };

Next.js Webhook Route Handler (Preserving Raw UTF-8 Bytes)

app/api/webhooks/route.ts
import crypto from "node:crypto";
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
  const rawBody = await req.text();
  const sig = req.headers.get("x-hub-signature-256") ?? "";
  const expected = "sha256=" + crypto.createHmac("sha256", process.env.WEBHOOK_SECRET!).update(rawBody, "utf8").digest("hex");

  if (sig.length !== expected.length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))) {
    return NextResponse.json({ error: "Invalid signature" }, { status: 401 });
  }
  const event = JSON.parse(rawBody);
  return NextResponse.json({ ok: true, id: event.id });
}

Key Engineering Takeaways

  • Static headers() in next.config.mjs only accept a single Access-Control-Allow-Origin string (either '*' or one domain) — multi-domain SaaS apps need middleware.ts or Route Handler helpers with Vary: Origin.
  • Always export an explicit OPTIONS handler (or intercept OPTIONS in middleware.ts) so Next.js does not answer preflight probes with 405 Method Not Allowed.
  • Do not mix matcher: ['/api/:path*'] CORS headers with webhook endpoints if you want strict server-to-server endpoints; webhooks never need CORS.

Common Production Pitfalls to Avoid

  • Deploying Next.js on Vercel behind edge caching without Vary: Origin causes CDN cache collisions between staging and production origins.
  • Calling await req.json() and re-stringifying inside a Next.js webhook Route Handler mutates whitespace and breaks HMAC-SHA256 verification.
  • Returning '*' in next.config.mjs while setting Access-Control-Allow-Credentials: 'true' causes immediate browser Fetch rejection.

More CORS & Webhook Signature Guides

← Back to CORS & Webhook HMAC Debugger Hub · OpenAPI OWASP API Top 10 & MCP Scorer → · SBOM & Sigstore Validator → · HTTP Security Headers & CSP →

Frequently Asked Questions

Can next.config.mjs headers() handle multiple allowed CORS origins?

Not cleanly — next.config.mjs only supports a single static header value or regex host matching that risks cache poisoning without custom Vary handling. Use middleware.ts for dynamic allowlists.

Why did Next.js return 405 Method Not Allowed on my CORS preflight?

App Router route.ts files only accept HTTP methods they explicitly export. Either export an OPTIONS(req) function or short-circuit req.method === 'OPTIONS' in middleware.ts.

How do I pair Next.js CORS with strict CSP security headers?

Use our Next.js Security Headers & CSP Guide (/security-headers/nextjs/) for page CSP/HSTS and apply CORS strictly to /api/:path*.