CORS & Preflight Simulator · Laravel 11/12 API + Next.js App Router

Laravel API + Next.js App Router CORS Simulator & Fix Guide

Simulate Fetch Standard preflight (OPTIONS) triggers, credential rules, and origin matching between Next.js App Router and Laravel 11/12 API. 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 (Next.js App Router)

2. Server Response Policy (Laravel 11/12 API)

Access-Control-Allow-Methods
<?php
// config/cors.php (Laravel 11/12 — run: php artisan config:publish cors)
// If using Laravel Sanctum SPA cookie auth, also set in .env:
// SANCTUM_STATEFUL_DOMAINS=localhost:3000
// SESSION_DOMAIN=localhost

return [
    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],

    'allowed_origins' => ['http://localhost:3000'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['Content-Type', 'Authorization', 'Accept', 'X-XSRF-TOKEN'],

    'exposed_headers' => [],

    'max_age' => 86400,

    'supports_credentials' => true,
];

Preflight (OPTIONS)

Triggered · Passed

HTTP method "PUT" is not a CORS-safelisted method (only GET, HEAD, and POST skip preflight). 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 '*, http://localhost:3000', 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: http://localhost:3000
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, Accept, X-XSRF-TOKEN
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Actual Response (PUT)
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Credentials: true
Vary: Origin

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

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:

DevTools Console Output

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.

  1. 1Publish and Lock Down Laravel CORS for Next.js Port 3000

    config/cors.php

    Publish 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,
    ];
  2. 2Configure Environment Variables for Local and Production Origins

    .env

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

    .envdotenv
    NEXTJS_ORIGIN=http://localhost:3000
    SANCTUM_STATEFUL_DOMAINS=localhost:3000
    SESSION_DOMAIN=localhost
  3. 3Configure Client Component Fetch With Explicit Credentials Mode

    src/lib/laravelClient.ts

    Inside 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();
    }
  4. 4Optional BFF Proxy Using Next.js Rewrites for Same-Origin Production Cookies

    next.config.ts

    If 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.tstypescript
    import 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.

Pitfall 1

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.

Pitfall 2

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.

Pitfall 3

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.

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 Laravel Octane & Reverb WebSockets.

Open Nginx Builder

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