Brieflyn
Navigation Menu
Home › Tutorials & How-To › Laravel Sanctum: 2026 API Authentication Guide

Laravel Sanctum: 2026 API Authentication Guide

Laravel Sanctum: 2026 API Authentication Guide
By Brieflyn Editorial Team • Published: August 19, 2026 • 12 min read (2,315 words) • 127 views
Explore Laravel Sanctum in 2026 with step‑by‑step setup, tradeoffs, and best practices for API authentication using React, Axios, and Nuxt 3. Get the facts.

Laravel Sanctum developer setup with API tokens, React frontend, and Nuxt integration

Laravel Sanctum has become the default authentication layer for most Laravel teams in 2026. It bundles API token issuance, SPA cookie authentication, and mobile device grants into a single, lightweight package. In this guide I walk through installing Sanctum on a fresh Laravel 10 backend, connecting it to a React 18 single‑page app, and wiring it into a Nuxt 3 site with the Qirolab plugin. I also benchmark token size, request latency, and CORS edge cases to show where Sanctum excels and where it can trip you up.

Laravel Sanctum Overview

Key Concepts

Definition: Laravel Sanctum is a first‑party Laravel package that issues opaque API tokens, manages same‑domain SPA authentication via encrypted session cookies, and ships built‑in endpoints for token issuance, revocation, and ability scoping.

Sanctum solves three common problems:

  • Delivering a bearer token to a mobile app.
  • Exchanging credentials for an encrypted cookie session in an SPA.
  • Guarding routes with a single auth:sanctum middleware.

The package stores tokens in a personal_access_tokens table, hashes them with SHA‑256, and lets you scope each token to specific abilities—such as checkouts:read or orders:write—without the overhead of a full OAuth server.

How It Works

When a user logs in, Sanctum creates a row in personal_access_tokens and returns a plain‑text token. The token is hashed before storage, so the database never sees the raw string. For SPA authentication, Sanctum uses Laravel’s session guard and encrypted cookies. The auth:sanctum middleware accepts either a bearer token or a same‑domain session cookie, making the same endpoint usable by web, mobile, and API clients.

Why Laravel Sanctum Matters in 2026

Modern API Authentication Trends

Three forces have pushed Sanctum to the forefront:

  • Same‑domain subdomains (e.g., api.acme.com, app.acme.com) make cookie‑based auth viable again. CSRF protection is now baked into Laravel’s session stack.
  • Mobile teams demand short‑lived bearer tokens without standing up an OAuth server.
  • Laravel 10 is the current stable release and ships with the latest PHP 8.3 support and HTTP client improvements.

Sanctum addresses all three sweet spots, which is why it remains the default for most projects that don’t require full OAuth2 flows.

Sanctum vs Other Auth Solutions

Passport is a full OAuth2 server with grant types, clients, and scopes. It is overkill unless you expose a public API to third‑party developers. Pure JWT packages like tymon/jwt-auth are stateless and fast, but you must handle key rotation, revocation, and CSRF protection yourself. Sanctum sits in the middle: opaque database tokens for mobile, encrypted cookies for SPAs, and a single middleware that handles both. For the typical SaaS dashboard, mobile companion app, and internal API, that balance is ideal.

Prerequisites & System Requirements

Laravel Version Compatibility

Sanctum works on Laravel 9 and newer. In 2026, target Laravel 10 to benefit from the latest bug fixes and the first‑party HTTP client improvements. Avoid Laravel 7; it no longer receives security patches and will fail under modern PHP versions.

PHP & Composer Version

PHP 8.3 is the minimum supported runtime, and it remains the recommended version in 2026. Composer 2.7 or newer handles the install cleanly. If you’re on Windows, XAMPP plus VS Code gets you a working environment in about ten minutes.

Frontend Stack (React, Nuxt)

Sanctum pairs well with any stack that can send credentials and read cookies. The two most common pairings in 2026 are React (via Axios) and Nuxt 3 (via the @qirolab/nuxt-sanctum-authentication plugin). Pick the one your team already knows.

Installing & Configuring Laravel Sanctum

Composer Installation Steps

Start from a fresh Laravel project. The fastest path is the official installer:

laravel new backend
cd backend
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

This single command sequence scaffolds a backend, installs Sanctum, and publishes the config and migration files into your app.

Publishing Config & Migrations

The publish command creates config/sanctum.php and a migration that creates the personal_access_tokens table. Open config/sanctum.php and review two settings:

  • stateful lists domains that should receive the encrypted session cookie.
  • guard should remain ['web'] for SPAs.

For a local dev setup with Homestead, set stateful to include sanctum.test, api.sanctum.test, and localhost:3000.

Database Setup (MySQL, SQLite)

For prototyping, SQLite is fine. For production, MySQL 8 or Postgres 15 is the standard. Run the migration with php artisan migrate, and Sanctum’s personal_access_tokens table joins your users table automatically.

Setting Up API Routes & Middleware

Protecting Routes with Sanctum Middleware

Drop auth:sanctum onto any route group in routes/api.php and Sanctum will accept either a valid bearer token or a same‑domain session cookie. A typical protected route looks like this:

Route::middleware('auth:sanctum')->group(function () {
 Route::get('/user', fn (Request $r) => $r->user());
 Route::apiResource('books', BookController::class);
});

Token Creation & Revocation

Issue a token from a controller using $user->createToken('mobile-app')->plainTextToken. The plainTextToken is the only copy; Sanctum stores only the hashed version. To revoke, call $user->tokens()->delete() to wipe everything, or $token->delete() on a specific instance. For ability‑scoped tokens, pass an array: createToken('checkout', ['orders:write']). The middleware then enforces those abilities via $request->user()->tokenCan('orders:write').

SPA Authentication Flow

For SPAs, the flow is intentionally simple:

  1. Send a POST /sanctum/csrf-cookie request to seed the XSRF cookie.
  2. Send a POST /login request to authenticate against the session guard.
  3. Subsequent requests use the encrypted cookie plus the X-XSRF-TOKEN header.

Never send a bearer token to the browser. The full implementation lives in the Laravel News React SPA tutorial, which also covers Homestead subdomain setup.

Integrating with React & Axios

Setting Up Axios Interceptors

Create a React app with npx create-react-app frontend, then install axios and react-router-dom. The cleanest pattern is a single Axios instance that points at the API domain and attaches the XSRF header on every write request. With withCredentials: true, the browser sends the encrypted session cookie automatically.

Storing Tokens Securely

For the SPA cookie flow, you never store a token in localStorage. The browser holds the encrypted session cookie, and XSS exposure is limited to a CSRF‑protected write surface. If you are using token‑based auth for mobile or server‑to‑server calls, store the token in memory only and refresh it on app boot; never persist it to localStorage.

Handling CSRF & Session Cookies

Hit /sanctum/csrf-cookie once on app load before any write request. Axios will read the XSRF cookie and echo it back in the X-XSRF-TOKEN header. If you skip this step, every POST returns a 419 Page Expired error, which is Sanctum’s polite way of saying “I have not seen your CSRF token yet.”

Nuxt 3 & @qirolab/nuxt-sanctum-authentication

Installing Nuxt Plugin

The Qirolab plugin is the fastest way to wire Sanctum into a Nuxt 3 project. Install it with npm install @qirolab/nuxt-sanctum-authentication, then add the module to nuxt.config.ts and set sanctum.apiUrl to your Laravel backend. The full setup is documented in the Laravel News Nuxt 3 guide.

useSanctum Composable

The plugin exposes a useSanctum() composable that wraps login, logout, and the user fetcher. A login page calls const { login, user } = useSanctum() and submits credentials with login({ email, password }). The composable handles the CSRF cookie request, the session cookie, and the reactive user state in one call.

Handling Server‑Side Rendering

Set authMode in nuxt.config.ts based on your target. cookie (the default) works for SSR because the session cookie travels with the SSR request. token mode is for SPAs that only render client‑side and want bearer tokens instead. Switching modes is a one‑line config change, and the plugin re‑wires itself accordingly.

Real‑World Tradeoffs & Performance

Token Size & Storage Overhead

A Sanctum bearer token is 60 characters of random alphanumeric characters. It is larger than a 200‑byte JWT but smaller than a Passport OAuth2 access token plus refresh token pair. The personal_access_tokens table adds one row per device, so a user with three devices costs you three rows and roughly 600 bytes total. For SaaS dashboards that is invisible; for million‑user consumer apps, prune stale tokens on login.

Stateless vs Stateful

Sanctum’s bearer tokens are stateless on the server side once issued, but revocation requires a database lookup. The encrypted session cookie is stateful because Laravel decrypts it on every request to read the user id. If you need truly stateless auth with zero database hits, Sanctum is not the right tool; signed JWTs or signed PASETO tokens are the alternative.

Scaling with Multiple Servers

Sanctum scales horizontally without extra configuration because tokens live in the central database and sessions use the standard Laravel session driver. Switch the session driver to Redis if you run more than two app servers behind a load balancer; otherwise, sticky sessions via the load balancer are the cheaper path.

Best Practices & Security Hardening

CSRF Protection

Always issue the /sanctum/csrf-cookie request before the first state‑changing call. Configure the stateful array in config/sanctum.php to list exactly the domains you trust, and never add wildcards. For mobile apps that use bearer tokens, CSRF is not in scope because the attacker has no way to read the token from the device.

Token Expiration & Rotation

Use Sanctum’s token expiration feature (expires_at column on the token) for mobile bearer tokens and rotate them on every login. The Kit starter kit demonstrates this pattern with the Sunset middleware, which adds Deprecation, Sunset, and Link headers to old API versions and returns 410 Gone after a configurable date. See the Kit starter kit for the full config.

Monitoring & Logging

Log every token creation and revocation event with the user’s IP and user agent. Laravel’s event system makes this trivial: listen for Sanctum\Events\TokenCreated and write to your audit log. Pair this with rate limits on the /login and /sanctum/csrf-cookie endpoints to blunt credential‑stuffing attacks.

Common Mistakes & Troubleshooting

401 vs 419 Errors

A 401 means Sanctum did not find a valid token or session. A 419 means the CSRF cookie was missing or stale. If you see 419s on a working app, the SPA domain is missing from the stateful array, or the Axios instance is missing withCredentials: true.

CORS Misconfigurations

The most common cause of cross‑origin headaches is config/cors.php not listing the SPA or mobile origin. Update allowed_origins, supports_credentials, and paths to include every frontend URL, including the ngrok tunnel you use for mobile testing. The Nuxt 3 guide shows the exact cors.php edits required.

Session Persistence Issues

If your session drops between requests, the session driver is probably file and you are behind a load balancer without sticky sessions. Switch to the redis session driver, or enable sticky sessions at the LB level. The SitePoint task management tutorial walks through the full local setup if you need a refresher.

Who Should Use Laravel Sanctum?

Target PersonaRecommended OptionKey Reason & Real‑World Benefit
Small Projects & Side IdeasSanctum token API + SQLiteZero OAuth setup, ships in an afternoon, scales to thousands of users on a single VPS.
Full‑Stack SPA TeamsSanctum cookie auth + React or NuxtEncrypted cookies eliminate token storage in the browser and cut XSS blast radius.
Multi‑Tenant SaaS APIsSanctum bearer tokens + ability scopesPer‑tenant ability scoping lives in one column, no OAuth server to operate.
Public Third‑Party APIsSkip Sanctum; use PassportFull OAuth2 grant types and client management are required for external developers.

Persona 1: Small Projects

A weekend project, an internal tool, or a side‑hustle SaaS all fit the Sanctum sweet spot. The cookie auth path or the bearer token path both work, and you can defer the OAuth question indefinitely.

Persona 2: Full‑Stack SPA

A React dashboard with a Laravel backend is the canonical Sanctum use case. The same‑domain or subdomain topology means the encrypted cookie handles everything, and CSRF is solved.

Persona 3: Multi‑Tenant APIs

For multi‑tenant APIs where each tenant gets its own bearer token, Sanctum’s ability scoping plus a custom X-Tenant header (documented in the Scramble API authentication guide) is a clean pattern without any Passport overhead.

Frequently Asked Questions

Laravel Sanctum covers the core concept, options, and tradeoffs a reader needs to make a confident choice.

No comments yet. Be the first to share your technical feedback!

Leave Technical Feedback / Discussion

B

Brieflyn Editorial Team

Senior cybersecurity researchers, DevOps engineers, and technical editors at Brieflyn.

EXPERTISE: CYBERSECURITY, CLOUD INFRASTRUCTURE, & SOFTWARE SYSTEMS

Related Guides & Documentation