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().
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.
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.
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.
Configure Nginx reverse-proxy CORS safely using map $http_origin, the always directive on 204/4xx/5xx responses, and Vary: Origin without breaking header inheritance.
Verify GitHub X-Hub-Signature-256 and Slack v0= webhook signatures using constant-time crypto.timingSafeEqual, raw request bytes, and timestamp replay protection.
Implement production-grade billing webhook HMAC-SHA256 verification for Stripe (`t=<ts>,v1=<hex>`) and Creem (`creem-signature: <hex>`) with raw-body preservation and replay checks.
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*.