Typical Runtime Error (Laravel Sanctum / SPA .env Failure)
When syntax errors, unquoted special characters, missing keys, or public-prefix secret leaks slip into a Laravel Sanctum / SPA .env file, your runtime or audit pipeline surfaces an error like the output below:
HTTP 419 Page Expired (CSRF token mismatch) — Browser dropped laravel_session & XSRF-TOKEN cookies because SESSION_DOMAIN and SANCTUM_STATEFUL_DOMAINS did not match the production HTTPS origin.
How Laravel Sanctum / SPA Loads .env Files, Precedence & Security Boundaries
Laravel Sanctum's SPA cookie authentication depends on five tightly synchronized .env variables: APP_URL, FRONTEND_URL, SANCTUM_STATEFUL_DOMAINS, SESSION_DOMAIN, and SESSION_SECURE_COOKIE. Misconfiguring even one character; such as leaving http://localhost:5173 in SANCTUM_STATEFUL_DOMAINS during production deployment, putting https:// inside SANCTUM_STATEFUL_DOMAINS, or forgetting the leading dot in SESSION_DOMAIN=.example.com; breaks stateful cookie sessions immediately.
A particularly confusing Sanctum bug happens when engineers move from localhost to production subdomains (app.example.com calling api.example.com). Locally, SANCTUM_STATEFUL_DOMAINS requires the port (localhost:5173) and SESSION_DOMAIN is localhost. In production over HTTPS port 443, SANCTUM_STATEFUL_DOMAINS must contain ONLY the bare hostname (app.example.com, with no https:// and no trailing slash), while SESSION_DOMAIN must include the leading dot (.example.com) and SESSION_SECURE_COOKIE=true.
If FRONTEND_URL has a trailing slash (https://app.example.com/), config/cors.php fails exact browser Origin comparison. Meanwhile, if APP_DEBUG=true slips into production alongside SESSION_DRIVER=cookie, debug output can expose encrypted payload details and misconfigured cookie flags.
Validating your Laravel Sanctum .env file with this browser-only checker flags leftover localhost domains in production mode, verifies APP_KEY cipher length, checks for missing SESSION_SAME_SITE or SESSION_SECURE_COOKIE keys against .env.example, and produces clean, quoted output ready for deployment.
After updating any Sanctum .env variables on staging or production, remember to run php artisan config:clear && php artisan config:cache and clear existing browser cookies on your test tab so stale session cookies from the old SESSION_DOMAIN do not linger.
Maintaining separate, clearly documented .env templates for local development (localhost:5173 + SESSION_DOMAIN=localhost) and HTTPS production subdomains (app.example.com + SESSION_DOMAIN=.example.com + SESSION_SECURE_COOKIE=true) prevents the most frustrating Laravel Sanctum 419 and 401 debugging loops. Whenever deploying Sanctum cookie changes, audit APP_URL, FRONTEND_URL, SANCTUM_STATEFUL_DOMAINS, and SESSION_DOMAIN together using the validator above, rebuild Laravel's config cache, and verify both Set-Cookie and Access-Control-Allow-Credentials headers in browser DevTools.
Step-by-Step Laravel Sanctum / SPA .env Configuration & Hardening Guide
Apply these four concrete safeguards to eliminate silent dotenv truncation, prevent secret leaks, and keep local and production environments synchronized.
1Align Production Sanctum Subdomain Variables in Laravel .env
.env (production)Use bare hostnames (no scheme, no trailing slash) in SANCTUM_STATEFUL_DOMAINS, share cookies across sibling subdomains with a leading-dot SESSION_DOMAIN, and require HTTPS cookies.
.env (production)dotenvAPP_ENV=production APP_DEBUG=false APP_URL=https://api.example.com FRONTEND_URL=https://app.example.com SANCTUM_STATEFUL_DOMAINS=app.example.com SESSION_DOMAIN=.example.com SESSION_DRIVER=redis SESSION_SECURE_COOKIE=true SESSION_SAME_SITE=lax2Wire FRONTEND_URL Cleanly Into config/cors.php With Credentials Enabled
config/cors.phpTrim any accidental trailing slashes defensively in config/cors.php and keep supports_credentials set to true for Sanctum SPAs.
config/cors.phpphpreturn [ 'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'], 'allowed_methods' => ['*'], 'allowed_origins' => [rtrim(env('FRONTEND_URL', 'http://localhost:5173'), '/')], 'allowed_headers' => ['Content-Type', 'Accept', 'X-XSRF-TOKEN', 'X-Requested-With'], 'supports_credentials' => true, ];3Keep Local Development Sanctum .env Consistent Across localhost
.env (local development)Include the Vite or Next.js port inside SANCTUM_STATEFUL_DOMAINS locally and never mix localhost with 127.0.0.1.
.env (local development)dotenvAPP_URL=http://localhost:8000 FRONTEND_URL=http://localhost:5173 SANCTUM_STATEFUL_DOMAINS=localhost:5173 SESSION_DOMAIN=localhost SESSION_SECURE_COOKIE=false4Clear Config Cache and Inspect Set-Cookie Headers With curl
terminalRebuild Laravel config cache and inspect the live /sanctum/csrf-cookie response headers to confirm Domain, Secure, and SameSite flags.
terminalbashphp artisan config:clear && php artisan config:cache curl -i https://api.example.com/sanctum/csrf-cookie -H "Origin: https://app.example.com"
Common Laravel Sanctum / SPA .env Pitfalls
Check these three framework-specific traps before deploying updated environment variables to staging or production.
Putting https:// Inside SANCTUM_STATEFUL_DOMAINS
Sanctum strips protocol schemes when comparing request Origin/Referer hosts against SANCTUM_STATEFUL_DOMAINS. Writing https://app.example.com instead of app.example.com prevents Sanctum from activating stateful session middleware.
Leaving SESSION_DOMAIN=localhost in Production
Browsers reject Set-Cookie headers whose Domain attribute does not match the responding host. Leaving SESSION_DOMAIN=localhost in production causes browsers to silently discard every session and XSRF-TOKEN cookie.
Deploying Frontend and API on Different Top-Level Domains With SameSite=lax
SESSION_DOMAIN=.example.com only works when both SPA and API share the same root domain (app.example.com + api.example.com). Separate root domains (vercel.app + company.com) are blocked as third-party cookies by Safari ITP.
Pair Your Validated .env With Webhook HMAC, Docker Compose & CORS Tools
Now that your environment variables are syntax-clean and leak-free, verify webhook raw-body HMAC signatures, container healthchecks, and browser cross-origin rules:
Verify Shopify X-Shopify-Hmac-Sha256 webhooks in Laravel 11/12 using base64_encode with binary hash_hmac, $request->getContent(), and hash_equals.
Generate a Docker Compose stack for Laravel Octane, PostgreSQL 16, Redis 7, and Laravel Reverb WebSockets with pg_isready healthchecks and firewall safety.
Fix Laravel Sanctum SPA cookie CORS errors. Validate supports_credentials, SANCTUM_STATEFUL_DOMAINS, X-XSRF-TOKEN preflight headers, and SameSite rules.
Frequently Asked Questions
- Should SESSION_DOMAIN start with a dot (.example.com) for Sanctum SPAs?
- Yes; setting SESSION_DOMAIN=.example.com allows cookies set by api.example.com to be sent back by app.example.com and any sibling subdomain cleanly.
- Can SANCTUM_STATEFUL_DOMAINS list multiple frontend domains?
- Yes. Separate multiple hostnames with commas and zero spaces: SANCTUM_STATEFUL_DOMAINS=app.example.com,admin.example.com.
- Why does /sanctum/csrf-cookie work locally but fail with 419 behind Nginx HTTPS?
- Ensure SESSION_SECURE_COOKIE=true, TrustProxies is configured in bootstrap/app.php so Laravel detects HTTPS behind Nginx, and Axios sets both withCredentials: true and withXSRFToken: true.
- Where should I verify the browser CORS headers matching these Sanctum .env values?
- Use our companion Laravel Sanctum SPA Cookie Auth CORS Simulator linked below to test exact preflight X-XSRF-TOKEN and Access-Control-Allow-Credentials headers.
Related Framework .env Guides
Browse all 10 .env guides →Laravel .env Validator & APP_KEY Checker (Fix Unquoted # & Config Errors)
Validate Laravel 11/12 .env files locally in your browser. Fix InvalidFileException, unquoted # in DB_PASSWORD, invalid base64 APP_KEY, and config:cache traps.
Next.js .env.local Validator & NEXT_PUBLIC_ Secret Leak Checker
Audit Next.js App Router .env.local and .env.production files in your browser. Catch NEXT_PUBLIC_ secret leaks, build-time inlining bugs, and missing keys.
Vite + React .env Checker (Fix VITE_ Prefix & Client Bundle Leaks)
Validate Vite and React .env files locally in your browser. Fix undefined import.meta.env keys, REACT_APP_ migration bugs, and VITE_ secret leaks.
Docker Compose .env Validator & $$ Dollar Escaping Checker
Fix Docker Compose .env substitution bugs and broken bcrypt hashes. Detect unescaped $ characters, spaces around =, and .env vs env_file differences locally.