Laravel

Laravel Sanctum for SPAs and Mobile Apps: Sessions, Tokens and Common Errors

Laravel Sanctum handles two different kinds of API client with one guard. A first-party SPA authenticates with Laravel's normal session cookie plus CSRF protection, while mobile apps and scripts authenticate with API tokens sent as Bearer headers. The auth:sanctum middleware accepts either.

Most Sanctum problems are configuration problems: a 419 CSRF error, a 401 right after a successful login, or cookies that never get sent. This guide sets up both modes on Laravel 11 or later and explains the settings behind those errors.

Understanding Laravel Sanctum's Approach

Sanctum isn't an OAuth2 server. If third-party applications need to request access on behalf of your users, use Laravel Passport or a dedicated identity provider. For your own SPA and mobile apps, Sanctum is usually all you need.

SPA mode uses the session cookie, so no token is ever stored in JavaScript, where an XSS bug could steal it. It has one hard requirement: the SPA and the API must share the same top-level domain (for example app.example.com and api.example.com). Browsers won't send the session cookie in the cross-site requests a SPA on a different domain would make. Sanctum treats a request as stateful when its Origin or Referer matches a domain in SANCTUM_STATEFUL_DOMAINS.

Token mode issues opaque tokens stored (hashed) in the personal_access_tokens table. Each token can carry a list of abilities (Sanctum's name for scopes) and an expiry date. Clients send it as Authorization: Bearer <token>.

Setup

Let's walk through how to integrate Laravel Sanctum into your application, covering both SPA authentication and API token management.

Step 1: Install and Configure Sanctum

On Laravel 11 and later, one command installs Sanctum, publishes its migration, and creates routes/api.php:

Bash
php artisan install:api
php artisan migrate

For SPA authentication, enable Sanctum's stateful middleware for API routes in bootstrap/app.php:

PHP
// bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->statefulApi();
})

statefulApi() adds Sanctum's EnsureFrontendRequestsAreStateful middleware, which turns on cookies, sessions and CSRF checks only for requests coming from your stateful domains. Token requests from mobile apps pass through unaffected. (On Laravel 10 and earlier, the equivalent is adding that middleware to the api group in app/Http/Kernel.php.)

Step 2: Prepare Your User Model

For Sanctum to associate API tokens with users, your User model (or any model you wish to issue tokens for) must use the HasApiTokens trait. This trait provides methods to manage tokens, such as createToken and tokens.

PHP
// app/Models/User.php

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    // ... rest of your model
}

Step 3: Implement SPA Authentication

Three settings have to agree with each other. For a SPA on app.example.com calling an API on api.example.com:

DOTENV
SANCTUM_STATEFUL_DOMAINS=app.example.com,localhost:5173   # include the port for local dev
SESSION_DOMAIN=.example.com        # leading dot: cookie shared across subdomains

And in config/cors.php (publish it with php artisan config:publish cors), allow credentials:

PHP
'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],
'allowed_origins' => ['https://app.example.com'],
'supports_credentials' => true,

What goes wrong when one of these is off:

  • 419 "CSRF token mismatch": the SPA didn't send the X-XSRF-TOKEN header, or the XSRF-TOKEN cookie was set for a different domain.
  • 401 right after a successful login: the SPA's origin isn't in SANCTUM_STATEFUL_DOMAINS (check the port), so Sanctum ignores the session cookie.
  • Cookies never sent: the frontend didn't set credentials: 'include' (fetch) or withCredentials: true (axios), or CORS doesn't allow credentials.

The SPA first calls /sanctum/csrf-cookie, which sets an XSRF-TOKEN cookie, then sends that value back in an X-XSRF-TOKEN header with the login request. Axios does the header part automatically. With fetch, read the cookie yourself:

JavaScript
const API = 'https://api.example.com';

function xsrfToken() {
  const match = document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]*)/);
  return match ? decodeURIComponent(match[1]) : '';
}

export async function login(email, password) {
  await fetch(`${API}/sanctum/csrf-cookie`, { credentials: 'include' });

  const res = await fetch(`${API}/login`, {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      'X-XSRF-TOKEN': xsrfToken(),
    },
    body: JSON.stringify({ email, password }),
  });

  if (!res.ok) throw new Error((await res.json()).message ?? 'Login failed');
}

The login route lives in routes/web.php, so it uses the web middleware stack (session and CSRF) automatically:

PHP
// routes/web.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

Route::post('/login', function (Request $request) {
    $credentials = $request->validate([
        'email' => ['required', 'email'],
        'password' => ['required'],
    ]);

    if (! Auth::attempt($credentials)) {
        return response()->json(['message' => 'Invalid credentials'], 401);
    }

    $request->session()->regenerate(); // prevents session fixation
    return response()->noContent();
})->middleware('throttle:5,1');

After login, the SPA calls auth:sanctum routes with credentials: 'include' and the X-XSRF-TOKEN header on any non-GET request. If you use Laravel Fortify or Breeze's API stack, they provide these login, logout and registration routes for you.

Step 4: Token-Based Authentication for Mobile Apps and Third Parties

For clients like mobile apps or other services that cannot rely on session cookies, you'll issue API tokens. Typically, you'd create an endpoint where users (or administrators acting on their behalf) can generate these tokens after authenticating with traditional credentials (email/password).

PHP
// routes/api.php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;

Route::post('/tokens/create', function (Request $request) {
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
        'device_name' => 'required|string|max:255',
    ]);

    $user = User::where('email', $request->email)->first();

    if (! $user || ! Hash::check($request->password, $user->password)) {
        return response()->json(['message' => 'Invalid credentials'], 401);
    }

    $token = $user->createToken(
        $request->device_name,
        ['orders:read', 'orders:write'],   // abilities
        now()->addDays(30),                // expiry
    )->plainTextToken;

    return response()->json(['token' => $token]);
})->middleware('throttle:5,1');            // slow down password guessing

The plain-text token is shown only once, since the database keeps a hash. Mobile apps should store it in the platform's secure storage (Keychain on iOS, Keystore-backed storage on Android), not in plain preferences. Clients send it on each request:

Code
Authorization: Bearer <token>

Tokens never expire by default. Pass an expiry as shown, or set expiration (in minutes) in config/sanctum.php, and schedule php artisan sanctum:prune-expired --hours=24 to delete old rows.

Step 5: Protecting Your API Routes

With Sanctum configured, protecting your API endpoints is as simple as applying the auth:sanctum middleware. This middleware will ensure that incoming requests have a valid API token or an authenticated session (for SPAs).

PHP
// routes/api.php

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::middleware(['auth:sanctum', 'abilities:orders:write'])
    ->post('/orders', [OrderController::class, 'store']);

The abilities middleware (register the alias for \Laravel\Sanctum\Http\Middleware\CheckAbilities in bootstrap/app.php) rejects tokens that lack the listed abilities. Inside a request, $request->user()->tokenCan('orders:write') does the same check. For SPA requests authenticated by session, tokenCan() always returns true, so abilities restrict tokens only. Use policies and gates for permissions that apply to every user regardless of how they logged in.

Step 6: Revoking API Tokens

Security best practices dictate that users should be able to revoke their API tokens, especially if a device is lost or compromised. Sanctum makes this easy.

PHP
// routes/api.php

Route::middleware('auth:sanctum')->delete('/tokens', function (Request $request) {
    // Revoke the current token
    $request->user()->currentAccessToken()->delete();

    return response()->json(['message' => 'Token revoked successfully']);
});

Route::middleware('auth:sanctum')->delete('/tokens/{id}', function (Request $request, $id) {
    // Revoke a specific token by ID (e.g., from an admin panel or user settings)
    $request->user()->tokens()->where('id', $id)->delete();

    return response()->json(['message' => 'Specific token revoked successfully']);
});

💡 Tip: Name tokens after the device or integration ("Pixel 8", "CI deploy script") and show users a list with last_used_at. That makes it obvious which token to revoke when a phone is lost.

Summary

  1. Use cookie sessions for your own SPA when it shares a top-level domain with the API, and keep SANCTUM_STATEFUL_DOMAINS, SESSION_DOMAIN and CORS supports_credentials consistent.
  2. Use tokens for mobile apps and scripts, with abilities, an expiry, and secure storage on the device.
  3. Rate-limit login and token endpoints, and regenerate the session after login.
  4. Let users see and revoke tokens, and prune expired tokens on a schedule.
Advertisement