Typical Browser Console Error (Next.js App Router → Laravel 11/12 API)
When cross-origin headers are missing, mismatched, or blocked during preflight between Next.js App Router and Laravel 11/12 API, Chrome and Firefox log an error matching the pattern below in DevTools:
Access to fetch at 'http://localhost:8000/api/orders' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
Why CORS Blocks Requests Between Next.js App Router and Laravel 11/12 API
Next.js App Router applications split data fetching across two completely different execution environments: React Server Components (running in Node.js or Edge workers) and Client Components (running inside the user's browser on http://localhost:3000). A major point of confusion when connecting Next.js to a Laravel API on http://localhost:8000 is that GET requests inside Server Components succeed with zero CORS headers, whereas the exact same fetch utility fails with a CORS policy error as soon as a user triggers a mutation inside a "use client" component.
Server-to-server HTTP requests from Next.js Server Components, Server Actions, or Route Handlers do not enforce browser CORS rules because CORS is strictly a browser security mechanism enforced by Blink, Gecko, and WebKit. However, browser-initiated mutations; such as updating an order via PUT or PATCH, submitting forms with credentials: "include", or sending Bearer tokens from Client Components; always trigger CORS validation and HTTP OPTIONS preflight handshakes against Laravel's HandleCors middleware.
Because Next.js frontends frequently combine session cookies or HttpOnly authentication tokens with JSON payloads, leaving Laravel's default allowed_origins set to * while flipping supports_credentials to true immediately violates the Fetch Standard. Browsers reject any response that pairs Access-Control-Allow-Origin: * with Access-Control-Allow-Credentials: true. Getting production parity right requires aligning config/cors.php, Laravel TrustProxies, and your Next.js environment variables across both server and browser runtimes.
When promoting a Laravel and Next.js App Router stack from localhost to production, verify that your reverse proxy or load balancer forwards X-Forwarded-Proto and X-Forwarded-Host cleanly to Laravel so URL generation, secure cookies, and CORS origin checks agree on HTTPS. In Chrome DevTools, filter the Network tab by Fetch/XHR and inspect both the OPTIONS preflight request and the subsequent GET or PUT request: confirm that Access-Control-Allow-Origin matches your exact Next.js deployment origin, Access-Control-Allow-Credentials equals true when cookies are attached, and Vary: Origin is present so edge caches never serve stale cross-origin headers.
Step-by-Step Laravel 11/12 API + Next.js App Router CORS Fix Guide
Follow each step below in order to eliminate preflight failures and lock down production origins safely for Laravel 11/12 API.
1Publish and Lock Down Laravel CORS for Next.js Port 3000
config/cors.phpPublish config/cors.php via php artisan config:publish cors and configure an explicit origin whitelist for your Next.js URL. Enable supports_credentials if your Next.js client forwards Laravel session cookies or Sanctum CSRF tokens, and explicitly enumerate every REST method and custom header your Client Components transmit.
config/cors.phpphp<?php return [ 'paths' => ['api/*', 'sanctum/csrf-cookie'], 'allowed_methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], 'allowed_origins' => [ env('NEXTJS_ORIGIN', 'http://localhost:3000'), ], 'allowed_origins_patterns' => [], 'allowed_headers' => [ 'Content-Type', 'Authorization', 'Accept', 'X-Requested-With', 'X-XSRF-TOKEN', ], 'exposed_headers' => [], 'max_age' => 86400, 'supports_credentials' => true, ];2Configure Environment Variables for Local and Production Origins
.envStore the exact scheme, host, and port of your Next.js deployment in .env without any trailing slash. When running Laravel behind a load balancer, Cloudflare proxy, or Nginx TLS terminator in production, configure TrustProxies in bootstrap/app.php so Laravel recognizes HTTPS requests and sets secure cookies accurately.
.envdotenvNEXTJS_ORIGIN=http://localhost:3000 SANCTUM_STATEFUL_DOMAINS=localhost:3000 SESSION_DOMAIN=localhost3Configure Client Component Fetch With Explicit Credentials Mode
src/lib/laravelClient.tsInside Next.js Client Components, pass credentials: "include" only when your Laravel endpoint requires cookies, and ensure every mutation sends Accept: application/json alongside Content-Type: application/json so Laravel never redirects an unauthenticated API request to an HTML login page.
src/lib/laravelClient.tstypescript'use client'; const API_URL = process.env.NEXT_PUBLIC_LARAVEL_API_URL ?? 'http://localhost:8000'; export async function updateOrder(orderId: string, status: string, token: string) { const res = await fetch(`${API_URL}/api/orders/${orderId}`, { method: 'PUT', credentials: 'include', headers: { 'Content-Type': 'application/json', Accept: 'application/json', Authorization: `Bearer ${token}`, }, body: JSON.stringify({ status }), }); if (!res.ok) { throw new Error(`Laravel API returned ${res.status}`); } return res.json(); }4Optional BFF Proxy Using Next.js Rewrites for Same-Origin Production Cookies
next.config.tsIf you want to avoid cross-site third-party cookie restrictions in Safari Intelligent Tracking Prevention while deploying Next.js and Laravel on completely different domains, proxy /backend/* through Next.js rewrites or Route Handlers so the browser communicates with a single first-party origin.
next.config.tstypescriptimport type { NextConfig } from 'next'; const nextConfig: NextConfig = { async rewrites() { return [ { source: '/backend/:path*', destination: `${process.env.LARAVEL_INTERNAL_URL ?? 'http://localhost:8000'}/api/:path*`, }, ]; }, }; export default nextConfig;
Common Laravel 11/12 API + Next.js App Router 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.
Forgetting Vary: Origin Behind CDNs and Reverse Proxies
If you serve multiple Next.js environments (such as Vercel preview deployments and production) from one Laravel API behind Cloudflare or CloudFront, caching an Access-Control-Allow-Origin response without Vary: Origin causes the CDN to hand staging's CORS header to production users, breaking browser requests intermittently across regions.
Using NEXT_PUBLIC_ Variables Incorrectly Across Server vs. Client Bundles
In Docker Compose setups, Next.js Server Components often reach Laravel via http://laravel:8000 on the internal Docker bridge network, while the user's browser must reach http://localhost:8000. Passing the internal container hostname into NEXT_PUBLIC_API_URL causes browser requests to fail with net::ERR_NAME_NOT_RESOLVED or mismatched CORS origins.
Missing PUT and PATCH in Custom Middleware or Firewall Rules
Some managed hosting WAFs, Apache configurations, or custom Laravel route constraints block OPTIONS, PUT, or PATCH methods before HandleCors runs. Always verify with curl that OPTIONS requests to /api/* return HTTP 204 with Access-Control-Allow-Methods containing PUT, PATCH, and DELETE.
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 Laravel Octane & Reverb WebSockets.
Frequently Asked Questions
- Why did my Next.js Server Component fetch work while my Client Component threw a CORS error?
- Next.js Server Components execute on your Node.js or Edge server, where no browser Same-Origin Policy exists. Client Components execute inside the visitor's browser, which enforces CORS preflights and inspects Access-Control-Allow-Origin headers on every cross-origin request sent directly to your Laravel API.
- Can Next.js Server Actions bypass Laravel CORS completely?
- Yes. Because Next.js Server Actions execute on the Next.js server, calling Laravel from inside a Server Action is a server-to-server HTTP call and does not trigger browser CORS checks. You must still forward authentication headers, client IP headers, or signed cookies carefully from the incoming Next.js request.
- What happens if supports_credentials is true but allowed_origins is still ["*"]?
- Even if Laravel responds with Access-Control-Allow-Origin: * and Access-Control-Allow-Credentials: true, every modern browser blocks the response per the Fetch Standard. You must list exact origins such as http://localhost:3000 in allowed_origins and verify that no trailing slash is present.
- How do I handle dynamic Vercel preview URLs with Laravel CORS?
- Use Laravel's allowed_origins_patterns array with a tightly scoped regular expression matching your project's preview subdomain format, such as #^https://my-app-[a-z0-9-]+\.vercel\.app$#. Avoid overly broad regex patterns that could allow attacker-controlled domains to make authenticated requests.
Related CORS Stack Simulators
Browse all 12 stacks →Laravel + React (Vite) CORS Config Simulator & Fix Guide
Simulate and fix CORS preflight errors between Laravel 11/12 APIs and React Vite on port 5173. Generate config/cors.php with credentials and header rules.
Laravel Sanctum SPA Cookie Auth CORS Simulator & Fix Guide
Fix Laravel Sanctum SPA cookie CORS errors. Validate supports_credentials, SANCTUM_STATEFUL_DOMAINS, X-XSRF-TOKEN preflight headers, and SameSite rules.
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.
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.