Laravel Sanctum SPA auth looks simple on paper: frontend hits /sanctum/csrf-cookie, then logs in, then sends session cookies with future API requests.

The part that trips people up is CORS. Not because CORS is complicated in theory, but because Sanctum relies on cookies + CSRF + stateful requests, and browsers get very picky when credentials are involved.

If your React, Vue, or Nuxt frontend lives on http://localhost:5173 and your Laravel API lives on http://localhost:8000, you’re in CORS territory immediately.

Here’s how to make it work reliably.

The Sanctum SPA auth flow

For SPAs, Sanctum does session-based authentication, not API tokens.

Typical flow:

  1. Frontend requests GET /sanctum/csrf-cookie
  2. Laravel sets:
    • XSRF-TOKEN
    • session cookie
  3. Frontend sends POST /login with:
    • credentials: 'include'
    • X-XSRF-TOKEN header
  4. Browser stores authenticated session cookie
  5. Future requests to /api/user or similar include cookies

That means your CORS setup must allow:

  • the SPA origin
  • credentials
  • CSRF-related headers
  • preflight requests where needed

If one piece is off, login usually fails with one of these classics:

  • CORS policy: No 'Access-Control-Allow-Origin' header
  • The value of the 'Access-Control-Allow-Credentials' header is '' which must be 'true'
  • 419 Page Expired
  • login appears successful, but /api/user returns unauthenticated

The biggest Sanctum+CORS rule

If you use cookies across origins, you cannot use:

Access-Control-Allow-Origin: *

That wildcard works for public APIs, not credentialed browser requests.

For example, GitHub can safely return:

access-control-allow-origin: *
access-control-expose-headers: ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, X-GitHub-SSO, X-GitHub-Request-Id, Deprecation, Sunset, Warning

That works because their public endpoints generally don’t depend on browser cookies for SPA auth. Sanctum does.

For Sanctum SPA auth, your response needs a specific origin, like:

Access-Control-Allow-Origin: http://localhost:5173
Access-Control-Allow-Credentials: true

Laravel CORS config for Sanctum

In modern Laravel apps, CORS is usually configured in config/cors.php.

A working local setup might look like this:

<?php

return [
    'paths' => [
        'api/*',
        'sanctum/csrf-cookie',
        'login',
        'logout',
        'register',
        'user',
    ],

    'allowed_methods' => ['*'],

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

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,
];

The two settings people miss most often:

  • sanctum/csrf-cookie must be in paths
  • supports_credentials must be true

If /sanctum/csrf-cookie is not covered by CORS middleware, the whole login flow breaks before it starts.

Sanctum stateful domains

Sanctum also needs to know which frontend domains should be treated as “stateful”.

In .env:

SANCTUM_STATEFUL_DOMAINS=localhost:5173,127.0.0.1:5173
SESSION_DOMAIN=localhost

And sometimes for local setups, especially if you’re mixing localhost and 127.0.0.1, consistency matters more than people expect. Pick one and stick to it.

If your SPA runs on 127.0.0.1:5173 but your stateful domains only list localhost:5173, I’d expect weird auth behavior.

In config/sanctum.php, Laravel reads this from env:

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
    '%s%s',
    'localhost,localhost:3000,localhost:8000,127.0.0.1,127.0.0.1:8000,::1',
    env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),

Make sure your actual SPA origin is in that list.

Sanctum SPA auth is cookie auth. So session settings matter.

In .env:

APP_URL=http://localhost:8000
SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost
SESSION_SECURE_COOKIE=false

For HTTPS production:

APP_URL=https://api.example.com
SESSION_DOMAIN=.example.com
SESSION_SECURE_COOKIE=true
SANCTUM_STATEFUL_DOMAINS=app.example.com

A common production pattern:

  • SPA: https://app.example.com
  • API: https://api.example.com

That’s cross-origin, but still same-site in many cases because they share the registrable domain example.com. That makes cookie behavior much less painful than truly cross-site setups.

If you split domains completely, like:

  • SPA: https://myfrontend.com
  • API: https://mybackend.com

you’re asking for more browser cookie restrictions. I avoid that unless there’s a strong reason.

Frontend requests that actually work

Here’s the fetch version.

await fetch('http://localhost:8000/sanctum/csrf-cookie', {
  method: 'GET',
  credentials: 'include',
});

Step 2: Log in

function getCookie(name) {
  return document.cookie
    .split('; ')
    .find(row => row.startsWith(name + '='))
    ?.split('=')[1];
}

const xsrfToken = decodeURIComponent(getCookie('XSRF-TOKEN') || '');

await fetch('http://localhost:8000/login', {
  method: 'POST',
  credentials: 'include',
  headers: {
    'Content-Type': 'application/json',
    'X-XSRF-TOKEN': xsrfToken,
    'Accept': 'application/json',
  },
  body: JSON.stringify({
    email: '[email protected]',
    password: 'secret',
  }),
});

Step 3: Call authenticated endpoint

const response = await fetch('http://localhost:8000/api/user', {
  method: 'GET',
  credentials: 'include',
  headers: {
    'Accept': 'application/json',
  },
});

const user = await response.json();
console.log(user);

If you use Axios, set this once:

import axios from 'axios';

axios.defaults.withCredentials = true;
axios.defaults.withXSRFToken = true;
axios.defaults.baseURL = 'http://localhost:8000';
axios.defaults.headers.common['Accept'] = 'application/json';

Then:

await axios.get('/sanctum/csrf-cookie');
await axios.post('/login', {
  email: '[email protected]',
  password: 'secret',
});
const { data } = await axios.get('/api/user');

Axios tends to be smoother with Sanctum because it already understands the CSRF-cookie pattern pretty well.

What the preflight should look like

A login request with JSON and custom headers usually triggers an OPTIONS preflight.

Browser sends something like:

OPTIONS /login
Origin: http://localhost:5173
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type,x-xsrf-token

Laravel should answer with something like:

Access-Control-Allow-Origin: http://localhost:5173
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, X-XSRF-TOKEN
Access-Control-Allow-Credentials: true
Vary: Origin

If the preflight fails, the real request never happens.

When debugging, I like checking the raw headers first instead of guessing. A header inspection tool like HeaderTest is handy for verifying what the server actually returns versus what I think it returns.

Common Sanctum CORS mistakes

1. Using * with credentials

Broken:

'allowed_origins' => ['*'],
'supports_credentials' => true,

Browsers reject that combination for credentialed requests.

Use explicit origins instead.

2. Forgetting credentials: 'include'

Without it, cookies are not sent or stored properly.

Broken:

fetch('http://localhost:8000/api/user');

Fixed:

fetch('http://localhost:8000/api/user', {
  credentials: 'include',
});

This one wastes a lot of time because everything else can look correct.

4. Mixing localhost and 127.0.0.1

Browsers treat them as different origins. Sanctum does too. Don’t casually switch between them.

5. Wrong session domain

For subdomain setups, use something like:

SESSION_DOMAIN=.example.com

That leading dot is often what makes cookies available across subdomains.

6. Proxy/CDN stripping headers

If you put Nginx, Cloudflare, or some ingress layer in front of Laravel, verify it’s not rewriting or dropping CORS headers. I’ve seen app code be fine while the edge layer quietly broke everything.

A production example

Say you have:

  • SPA: https://app.example.com
  • API: https://api.example.com

config/cors.php:

return [
    'paths' => [
        'api/*',
        'sanctum/csrf-cookie',
        'login',
        'logout',
    ],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['https://app.example.com'],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 600,
    'supports_credentials' => true,
];

.env:

APP_URL=https://api.example.com
SANCTUM_STATEFUL_DOMAINS=app.example.com
SESSION_DOMAIN=.example.com
SESSION_SECURE_COOKIE=true

That’s the setup I’d reach for first. Clean, predictable, and friendly to browser cookie rules.

When exposed headers matter

Sanctum auth itself usually doesn’t need Access-Control-Expose-Headers, but your app might.

GitHub exposes useful headers like:

  • ETag
  • Link
  • Retry-After
  • rate limit headers

That’s why browser JS can read them when calling api.github.com. If your Laravel API returns custom pagination, rate limit, or versioning headers and you want frontend JS to read them, expose them explicitly:

'exposed_headers' => [
    'X-RateLimit-Remaining',
    'X-RateLimit-Reset',
    'Link',
],

Without that, the browser may receive the headers but hide them from JavaScript.

Security angle

CORS is not an auth system. It’s a browser access control layer.

Sanctum’s real security comes from:

  • session cookies
  • CSRF protection
  • proper SameSite/secure cookie settings
  • normal Laravel auth/session controls

If you’re auditing the broader header setup too, that’s where CSP, HSTS, and friends enter the picture. For that side of things, csp-guide.com is useful.

My practical checklist

When Sanctum SPA auth fails, I check these in order:

  1. Does /sanctum/csrf-cookie return CORS headers?
  2. Is Access-Control-Allow-Origin the exact SPA origin?
  3. Is Access-Control-Allow-Credentials: true present?
  4. Is frontend using credentials: 'include' or withCredentials = true?
  5. Is the SPA origin listed in SANCTUM_STATEFUL_DOMAINS?
  6. Is SESSION_DOMAIN correct for the deployment shape?
  7. Are localhost and 127.0.0.1 mixed?
  8. Does the OPTIONS preflight succeed?
  9. Are cookies actually being set in the browser devtools?
  10. Is a proxy altering headers?

Most Sanctum+CORS bugs come down to one of those.

If you remember only one thing, remember this: Sanctum SPA auth is cookie auth, and cookie auth means CORS must be configured for credentials, not for public wildcard access. That’s the whole game.