The Complete Production SOP: How to Deploy and Run Laravel Sanctum SPA Authentication & API Token Management in Autonomous AI Agents
Production SOP to run Laravel Sanctum SPA auth in Codex, Claude Code, Cursor, and Windsurf. Configure CSRF cookies, API token abilities, and CORS state safely.
Technical Overview & Architectural Context
Autonomous coding agents frequently fail when configuring hybrid authentication architectures involving Laravel Sanctum, modern frontends (Next.js, Vue, Nuxt), and mobile endpoints. Without strict domain constraints, agents routinely conflate standard stateless API token workflows (Bearer tokens) with session-based SPA authentication. This leads to broken implementations where agents attempt to send Bearer tokens to stateful endpoints, omit the critical pre-flight CSRF cookie handshake (`/sanctum/csrf-cookie`), or inject flawed CORS and `SESSION_DOMAIN` configurations that silently drop session cookies across localhost ports. The `laravel-sanctum-spa-auth` skill formalizes a deterministic operational boundary. It enforces precise separation of concerns: stateful cookie-based authentication for browser SPAs via `EnsureFrontendRequestsAreStateful` and cryptographically hashed Personal Access Tokens with granular abilities (`createToken(name, abilities)`) for third-party or mobile API clients. By establishing exact operational order—CORS alignment, session domain verification, CSRF initialization, credentialed exchange, and token ability authorization—the agent executes authentication tasks without hallucinated middleware structures or security misconfigurations.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Mount the deterministic Sanctum authentication skill into the agent's active execution registry.
Autonomous runtimes such as Claude Code and Cursor look for procedural skills within the `.agents/skills` or `.cursor/rules` workspace directories. Mounting the raw `SKILL.md` ensures that triggers like 'setup laravel sanctum spa' and 'csrf cookie sanctum nextjs' activate the strict execution SOP, constraining filesystem modifications to Laravel's configuration and middleware pipelines.
mkdir -p .agents/skills/laravel-sanctum-spa-auth && curl -fsSL https://askills.dev/api/skills/laravel-sanctum-spa-auth/raw -o .agents/skills/laravel-sanctum-spa-auth/SKILL.md---
name: "laravel-sanctum-spa-auth"
description: "Authenticate Single Page Applications (Next/Vue) and mobile apps with Laravel Sanctum."
metadata:
author: "Laravel"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "setup laravel sanctum spa"
- "csrf cookie sanctum nextjs"
- "api token abilities sanctum"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---Mount the skill locally in the project root rather than globally so the agent scopes CORS and domain configs strictly to the current repository structure without token bloat.
Ensure `fs_write` is limited to 'workspace'. Do not allow shell execution privileges unless explicitly validating migrations or route cache clearing.
Environment Secrets & Stateful Domain Configuration
Define environment variables for stateful domain resolution, session boundaries, and CORS.
Sanctum uses the `SANCTUM_STATEFUL_DOMAINS` variable to inspect incoming request referrers and origins. If this variable is improperly formatted or missing the frontend port, Sanctum falls back to stateless token authentication, resulting in persistent 419 CSRF failures. In this step, the agent binds frontend client origins into both `.env` and `config/sanctum.php`.
php -r "file_put_contents('.env', PHP_EOL.'SANCTUM_STATEFUL_DOMAINS=localhost:3000,127.0.0.1:3000'.PHP_EOL.'SESSION_DOMAIN=localhost'.PHP_EOL, FILE_APPEND);"<?php
return [
'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],
'allowed_methods' => ['*'],
'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:3000')],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];Always ensure `supports_credentials => true` in `config/cors.php`; otherwise, browsers will strip the `Set-Cookie` header during the `/sanctum/csrf-cookie` request.
When developing on `localhost`, avoid prefixing `SESSION_DOMAIN` with a leading dot (`.localhost`), as modern Chromium-based browsers reject wildcard localhost cookies.
Middleware Injection & Route Protection
Activate EnsureFrontendRequestsAreStateful middleware and configure abilities for token routes.
In Laravel 11, middleware configuration is defined in `bootstrap/app.php` rather than `app/Http/Kernel.php`. The skill instructs the agent to detect the framework version and inject `EnsureFrontendRequestsAreStateful` into the API group. Furthermore, for mobile/service clients, routes must be guarded using `auth:sanctum` combined with ability assertions.
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
// Stateful SPA authenticated user
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
// Token issuance with explicit abilities for mobile/external consumers
Route::post('/tokens/create', function (Request $request) {
$request->validate(['token_name' => 'required|string']);
$token = $request->user()->createToken($request->token_name, ['orders:create', 'orders:read']);
return response()->json(['token' => $token->plainTextToken]);
})->middleware('auth:sanctum');
// Route protected by granular ability
Route::middleware(['auth:sanctum', 'ability:orders:create'])->post('/orders', function (Request $request) {
return response()->json(['status' => 'Order created']);
});Direct the agent to use `ability` (requires all specified abilities) or `abilities` (requires any specified ability) middleware aliases depending on your authorization design.
Do not duplicate `EnsureFrontendRequestsAreStateful` on web routes; it is designed strictly to inspect requests traversing the API middleware stack.
Verification, Linting & Output Quality Gate
Run static analysis, route verification, and automated tests to ensure no regressions.
Before marking the authentication implementation complete, the agent runs Laravel's route listing to verify that middleware bindings are compiled, followed by PHPStan/Pint checks to ensure compliance with workspace type safety and formatting conventions.
php artisan route:list --path=sanctum && ./vendor/bin/pint --test && php artisan test --filter=AuthenticationTestInspect the output of `php artisan route:list` to verify that `/sanctum/csrf-cookie` is successfully registered under the web middleware group.
If tests fail with database connection errors, ensure the agent runs tests with `RefreshDatabase` against an in-memory SQLite database (`:memory:`) to prevent polluting production credentials.
Real-World Scenario: Configuring Next.js 14 App Router SPA Authentication against Laravel 11 Sanctum Backend
“Set up Laravel Sanctum SPA authentication for our Next.js frontend running at localhost:3000. Configure CSRF cookies, set the stateful domains, protect the /api/v1/profile route with auth:sanctum, and add a mobile token issuance route with 'read:profile' ability.”
Runtime Troubleshooting & Failure Modes
Root Cause: The frontend application failed to call GET /sanctum/csrf-cookie before initiating the POST request, or the client HTTP library (e.g., Axios/Fetch) omitted credentials, preventing the XSRF-TOKEN cookie from being stored and sent via the X-XSRF-TOKEN header.
axios.defaults.withCredentials = true;
await axios.get('http://localhost:8000/sanctum/csrf-cookie');
await axios.post('http://localhost:8000/login', { email, password });Root Cause: The incoming Origin or Referer header does not match the domains listed in SANCTUM_STATEFUL_DOMAINS, causing Sanctum to bypass stateful cookie authentication and demand a Bearer token.
# In .env, verify exact port matching:
SANCTUM_STATEFUL_DOMAINS=localhost:3000,127.0.0.1:3000
# Re-cache configuration:
php artisan config:clearFrequently Asked Questions (Laravel Sanctum SPA Authentication & API Token Management SOP)
Q:Can I use Laravel Sanctum SPA Authentication & API Token Management across Codex, Claude Code, and Cursor simultaneously?
Yes. The skill conforms to the universal SKILL.md specification. Runtimes read the frontmatter YAML triggers and execution SOP uniformly, whether invoked via Claude Code CLI commands, Codex Desktop completions, Cursor Composer rules, or Windsurf Cascades.
Q:How does Laravel Sanctum SPA Authentication & API Token Management prevent context window overflow during long agent sessions?
By establishing concise procedural boundaries and deterministic validation gates rather than polluting system prompts with redundant rules. The agent receives only the targeted domain steps (CORS verification, stateful domain alignment, token ability checks) when explicit triggers match.
Q:Does this skill require escalated root or container permissions?
No. It is audited with a security score of 98/100 and runs safely within workspace-scoped sandboxes (`fs_write: workspace`, `shell_exec: false`). It relies entirely on standard framework configuration files and route definitions without host-level escalation.
Ready to equip your autonomous agent with Laravel Sanctum SPA Authentication & API Token Management?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.