CORS & Preflight Simulator · Laravel Sanctum API + SPA (Cookie Auth)

Laravel Sanctum SPA Cookie Auth CORS Simulator & Fix Guide

Simulate Fetch Standard preflight (OPTIONS) triggers, credential rules, and origin matching between SPA (Cookie Auth) and Laravel Sanctum 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 (SPA (Cookie Auth))

2. Server Response Policy (Laravel Sanctum 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:5173
// SESSION_DOMAIN=localhost

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

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

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

    'allowed_origins_patterns' => [],

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

    'exposed_headers' => [],

    'max_age' => 86400,

    'supports_credentials' => true,
];

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): X-XSRF-TOKEN, X-Requested-With.

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:5173', 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:5173
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Accept, X-XSRF-TOKEN, X-Requested-With
Access-Control-Allow-Credentials: true
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: http://localhost:5173
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 (SPA (Cookie Auth) → Laravel Sanctum API)

When cross-origin headers are missing, mismatched, or blocked during preflight between SPA (Cookie Auth) and Laravel Sanctum API, Chrome and Firefox log an error matching the pattern below in DevTools:

DevTools Console Output

Access to XMLHttpRequest at 'http://localhost:8000/sanctum/csrf-cookie' from origin 'http://localhost:5173' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.

Why CORS Blocks Requests Between SPA (Cookie Auth) and Laravel Sanctum API

Laravel Sanctum's SPA authentication mode relies on first-party encrypted session cookies and an XSRF-TOKEN cookie rather than storing long-lived Bearer JWTs in browser localStorage. While this protects tokens from basic JavaScript XSS exfiltration, it introduces strict browser CORS and cookie-sharing requirements across four tightly coupled layers: config/cors.php, SANCTUM_STATEFUL_DOMAINS, SESSION_DOMAIN, and your frontend HTTP client's credentials flag.

Before a user logs in, your SPA calls GET /sanctum/csrf-cookie with credentials enabled so Laravel sets both the laravel_session and XSRF-TOKEN cookies. On every subsequent POST, PUT, PATCH, or DELETE request, Axios or Fetch must transmit those cookies back and attach the URL-decoded X-XSRF-TOKEN request header. Because X-XSRF-TOKEN is a non-safelisted custom header, the browser always fires a credentialed OPTIONS preflight request before your login or API controller runs.

If any single link in this handshake is misaligned; such as supports_credentials left as false, allowed_origins left as *, X-XSRF-TOKEN omitted from allowed_headers, /sanctum/csrf-cookie missing from paths, or your SPA served on localhost while Laravel runs on 127.0.0.1; the browser either blocks the preflight outright or silently refuses to store or transmit the session cookie, producing frustrating 419 CSRF Token Mismatch or 401 Unauthenticated errors.

Before deploying Laravel Sanctum SPA authentication to production, verify cookie behavior across Chrome, Firefox, and Safari using real HTTPS subdomains such as app.yourdomain.com and api.yourdomain.com rather than relying solely on localhost testing. Open DevTools Application -> Cookies after calling /sanctum/csrf-cookie and verify that both XSRF-TOKEN and your encrypted session cookie appear with Domain=.yourdomain.com, SameSite=Lax, and Secure=true. Any yellow warning triangle next to a Set-Cookie response header in the Network tab immediately reveals whether a domain mismatch, missing Secure flag, or SameSite policy prevented the browser from persisting the Sanctum session.

Step-by-Step Laravel Sanctum API + SPA (Cookie Auth) CORS Fix Guide

Follow each step below in order to eliminate preflight failures and lock down production origins safely for Laravel Sanctum API.

  1. 1Enable Credentialed CORS and Include /sanctum/csrf-cookie Path

    config/cors.php

    Publish config/cors.php and ensure paths includes api/*, sanctum/csrf-cookie, and any Fortify or Breeze authentication routes like login and logout that live outside the /api prefix. Set supports_credentials to true and replace * with your explicit SPA origin.

    config/cors.phpphp
    <?php
    
    return [
        'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],
    
        'allowed_methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
    
        'allowed_origins' => [
            env('FRONTEND_URL', 'http://localhost:5173'),
        ],
    
        'allowed_origins_patterns' => [],
    
        'allowed_headers' => [
            'Content-Type',
            'Accept',
            'X-XSRF-TOKEN',
            'X-Requested-With',
        ],
    
        'exposed_headers' => [],
    
        'max_age' => 86400,
    
        'supports_credentials' => true,
    ];
  2. 2Align SANCTUM_STATEFUL_DOMAINS and SESSION_DOMAIN in .env

    .env

    Sanctum only activates encrypted session and CSRF middleware for incoming requests whose Origin or Referer matches SANCTUM_STATEFUL_DOMAINS; including the non-default port number during local development. SESSION_DOMAIN must match the shared top-level domain: use localhost locally or .yourdomain.com in production when frontend and API live on sibling subdomains.

    .envdotenv
    APP_URL=http://localhost:8000
    FRONTEND_URL=http://localhost:5173
    SANCTUM_STATEFUL_DOMAINS=localhost:5173
    SESSION_DOMAIN=localhost
    SESSION_SAME_SITE=lax
    SESSION_SECURE_COOKIE=false
  3. 3Enable Stateful API Middleware in Laravel 11/12 Bootstrap

    bootstrap/app.php

    In Laravel 11 and 12, stateful SPA middleware is registered via $middleware->statefulApi() inside bootstrap/app.php instead of the legacy app/Http/Kernel.php file. Without this declaration, Sanctum ignores session cookies on /api/* routes and rejects requests with 401 Unauthenticated.

    bootstrap/app.phpphp
    <?php
    
    use Illuminate\Foundation\Application;
    use Illuminate\Foundation\Configuration\Exceptions;
    use Illuminate\Foundation\Configuration\Middleware;
    
    return Application::configure(basePath: dirname(__DIR__))
        ->withRouting(
            web: __DIR__.'/../routes/web.php',
            api: __DIR__.'/../routes/api.php',
        )
        ->withMiddleware(function (Middleware $middleware) {
            $middleware->statefulApi();
        })
        ->withExceptions(function (Exceptions $exceptions) {
            //
        })->create();
  4. 4Configure Axios With Credentials and Automatic XSRF Forwarding

    src/lib/axios.ts

    Axios 1.6 and newer require BOTH withCredentials: true and withXSRFToken: true when sending cookies cross-origin across different ports or subdomains. Always call /sanctum/csrf-cookie once before submitting credentials to initialize the session and XSRF cookie.

    src/lib/axios.tstypescript
    import axios from 'axios';
    
    export const api = axios.create({
      baseURL: 'http://localhost:8000',
      withCredentials: true,
      withXSRFToken: true,
      headers: {
        Accept: 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
      },
    });
    
    export async function login(email: string, password: string) {
      await api.get('/sanctum/csrf-cookie');
      return api.post('/login', { email, password });
    }

Common Laravel Sanctum API + SPA (Cookie Auth) 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

Axios 1.6+ Skipping the X-XSRF-TOKEN Header on Cross-Origin Ports

Starting in Axios 1.6.2, Axios stopped automatically copying the XSRF-TOKEN cookie into the X-XSRF-TOKEN request header on cross-origin requests unless you explicitly set withXSRFToken: true. Missing this single flag causes Laravel to reject every POST with 419 Page Expired even when CORS headers pass cleanly.

Pitfall 2

Using Completely Separate Registrable Domains in Production

Sanctum SPA cookies require your frontend and Laravel API to share the same registrable top-level domain (such as app.example.com and api.example.com with SESSION_DOMAIN=.example.com). Deploying your SPA to my-app.vercel.app and Laravel to api.my-company.com makes cookies third-party, which Safari and modern privacy-focused browsers block by default.

Pitfall 3

Omitting the Port Number in SANCTUM_STATEFUL_DOMAINS

Writing SANCTUM_STATEFUL_DOMAINS=localhost instead of localhost:5173 prevents Sanctum from recognizing requests originating from Vite's dev server port. Always include the non-standard port locally and omit ports only for default 80/443 production hosts.

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 does /sanctum/csrf-cookie succeed with 204 but /api/user still returns 401?
A 204 on /sanctum/csrf-cookie only proves CORS allowed the initial GET request. If /api/user returns 401, inspect three things: whether the browser actually stored the cookie in DevTools Application -> Cookies (look for SameSite or Domain mismatch warnings), whether both apps use localhost instead of 127.0.0.1, and whether $middleware->statefulApi() is enabled in bootstrap/app.php.
Should SESSION_SAME_SITE be lax or none for Laravel Sanctum SPAs?
Keep SESSION_SAME_SITE=lax whenever your SPA and Laravel API share the same root domain (e.g., app.example.com and api.example.com). Only use SameSite=none (which also mandates HTTPS and SESSION_SECURE_COOKIE=true) if cross-site requests are unavoidable; though migrating both apps onto subdomains of the same root domain is far more reliable.
Why does the browser complain about wildcard * in Access-Control-Allow-Headers when credentials are true?
Under the WHATWG Fetch Standard, wildcard * in Access-Control-Allow-Headers, Access-Control-Allow-Methods, and Access-Control-Allow-Origin is never treated as a wildcard whenever credentials mode is include. List X-XSRF-TOKEN, Content-Type, Accept, and X-Requested-With explicitly in config/cors.php.
Do I need both X-CSRF-TOKEN and X-XSRF-TOKEN in allowed_headers?
Laravel's VerifyCsrfToken middleware accepts encrypted tokens via X-XSRF-TOKEN (automatically read from the XSRF-TOKEN cookie by Axios) and unencrypted tokens via X-CSRF-TOKEN. Allowing X-XSRF-TOKEN is essential for Sanctum SPAs, and including both is safe if legacy views or custom fetch helpers submit X-CSRF-TOKEN.
Browse all 12 stacks →