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:
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.
1Enable Credentialed CORS and Include /sanctum/csrf-cookie Path
config/cors.phpPublish 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, ];2Align SANCTUM_STATEFUL_DOMAINS and SESSION_DOMAIN in .env
.envSanctum 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.
.envdotenvAPP_URL=http://localhost:8000 FRONTEND_URL=http://localhost:5173 SANCTUM_STATEFUL_DOMAINS=localhost:5173 SESSION_DOMAIN=localhost SESSION_SAME_SITE=lax SESSION_SECURE_COOKIE=false3Enable Stateful API Middleware in Laravel 11/12 Bootstrap
bootstrap/app.phpIn 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();4Configure Axios With Credentials and Automatic XSRF Forwarding
src/lib/axios.tsAxios 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.tstypescriptimport 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.
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.
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.
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.
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 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.
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 API + Next.js App Router CORS Simulator & Fix Guide
Debug CORS between Laravel 11/12 APIs and Next.js App Router on port 3000. Separate Server Component fetches from Client Component browser preflights.
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.
Nginx Reverse Proxy + Docker API CORS Simulator & Fix Guide
Fix Nginx reverse proxy CORS bugs for Docker APIs. Prevent duplicate Access-Control-Allow-Origin headers, add always on 4xx/5xx errors, and handle OPTIONS 204.