Have you encountered a 419 Page Expired or CSRF token mismatch error while working with a Laravel application?
This error commonly occurs when submitting forms, making AJAX requests, implementing authentication, or deploying an application to production.
For example, your application might work perfectly on your local machine but return a 419 error after deployment.
In most cases, Laravel cannot validate the CSRF token against the current user session. Missing tokens, expired sessions, incorrect cookies, and authentication configuration can all contribute to the problem.
In this guide, we'll explore the most common causes and demonstrate practical solutions using Laravel Blade, Axios, Fetch API, and Sanctum.
1. What Causes Laravel CSRF Token Mismatch (419 Error)?
CSRF stands for Cross-Site Request Forgery. It is a security attack in which an attacker attempts to make an authenticated user's browser perform an unwanted action without their knowledge.
Laravel protects against these attacks using CSRF tokens.
When a user accesses an application, Laravel associates a CSRF token with their session. For state-changing requests, such as POST, PUT, PATCH, and DELETE, Laravel verifies the submitted token against the current session.
If the token is missing, invalid, or does not match the session, Laravel rejects the request.
You may encounter an error similar to:
419 Page Expired
Or an exception such as:
Illuminate\Session\TokenMismatchException
Common causes
| Cause | Explanation |
|---|---|
| Missing CSRF token | Blade form does not contain @csrf. |
| Expired session | The user's session is no longer valid. |
| Incorrect AJAX configuration | JavaScript does not send the required token. |
| Cookie problems | Browser does not send the expected session cookie. |
| Domain mismatch | Frontend and backend cookie configurations are incompatible. |
| HTTPS configuration | Secure cookie settings conflict with the request scheme. |
| Sanctum configuration | SPA authentication is incorrectly configured. |
| Deployment issues | Session storage, encryption keys, or proxy configuration differ between environments. |
Before changing your application configuration, identify which of these situations applies to your request.
2. Fix Missing CSRF Tokens in Laravel Blade Forms
A missing CSRF token is one of the simplest causes of a 419 error.
Whenever you create a state-changing HTML form in Laravel, include the @csrf Blade directive.
Incorrect implementation
<form method="POST" action="{{ route('users.store') }}">
<input type="text" name="name" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
This form does not include a CSRF token, so Laravel's CSRF middleware may reject the request.
Correct implementation
Add @csrf inside the form:
<form method="POST" action="{{ route('users.store') }}">
@csrf
<input type="text" name="name" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
Laravel generates a hidden input containing the current session's CSRF token.
For example:
<input type="hidden" name="_token" value="generated-csrf-token">
What about PUT, PATCH, and DELETE requests?
HTML forms natively support GET and POST methods. Laravel provides @method to simulate other HTTP methods.
For example:
<form method="POST" action="{{ route('users.update', $user->id) }}">
@csrf
@method('PUT')
<input type="text" name="name" value="{{ $user->name }}">
<button type="submit">Update User</button>
</form>
The same principle applies to DELETE requests.
Remember: Include @csrf in every state-changing Blade form that uses Laravel's CSRF-protected web middleware.
3. Fix CSRF Errors in AJAX, Axios, and Fetch API Requests
JavaScript requests do not automatically include the hidden _token field from a Blade form.
If your application uses AJAX, Axios, or Fetch API, configure the request to send the appropriate CSRF token.
Step 1: Add the CSRF meta tag
Inside your main Blade layout, add:
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
This makes the current session's CSRF token accessible to JavaScript.
Step 2: Configure Axios
If your application uses Axios, you can configure the CSRF header globally:
const token = document.querySelector('meta[name="csrf-token"]')?.content;
if (token) {
axios.defaults.headers.common['X-CSRF-TOKEN'] = token;
}
Now Axios can include the token in subsequent requests.
Example:
axios.post('/users', {
name: 'Example User',
email: 'user@example.com'
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error.response?.data || error.message);
});
Step 3: Configure Fetch API
If you prefer native JavaScript, you can send the token manually:
const token = document.querySelector('meta[name="csrf-token"]').content;
fetch('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-CSRF-TOKEN': token
},
body: JSON.stringify({
name: 'Example User',
email: 'user@example.com'
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
X-CSRF-TOKEN vs. X-XSRF-TOKEN
Laravel also provides an XSRF-TOKEN cookie.
JavaScript libraries such as Axios can read this cookie and send its value through the X-XSRF-TOKEN request header when configured appropriately.
| Header | Token source |
|---|---|
X-CSRF-TOKEN |
HTML meta tag |
X-XSRF-TOKEN |
Laravel's XSRF-TOKEN cookie |
These are alternative ways of supplying the CSRF token. Do not confuse their values or manually combine them.
4. Troubleshoot Laravel Sessions and Cookies
Laravel associates CSRF tokens with user sessions. If the session expires or cannot be retrieved, a previously generated token may no longer match the current session.
Common causes include:
-
Users leaving forms open for extended periods.
-
Session storage becoming unavailable.
-
Browser cookies not being persisted.
-
Incorrect session configuration.
-
Multiple application servers using inconsistent session storage.
Check your session configuration
Open your .env file:
SESSION_DRIVER=file
SESSION_LIFETIME=120
SESSION_DRIVER determines where Laravel stores session data, while SESSION_LIFETIME specifies the session lifetime in minutes.
Common session drivers include:
| Driver | Storage |
|---|---|
| file | Local filesystem |
| database | Database table |
| redis | Redis |
| memcached | Memcached |
| cookie | Encrypted browser cookie |
| array | In-memory; not persisted between requests |
If you use file-based sessions, verify that Laravel can write to:
storage/framework/sessions
For database sessions, verify that the sessions table exists. For Redis, check that the service is running and Laravel can connect to it.
Check cookie domain and HTTPS configuration
Cookie configuration becomes particularly important when your frontend and backend use different subdomains.
For example:
Frontend: https://app.example.com
Backend: https://api.example.com
If the browser does not send the expected session cookie, Laravel may treat the request as belonging to a different session.
For applications that need to share cookies across subdomains, you may configure:
SESSION_DOMAIN=.example.com
For HTTPS applications, also review:
SESSION_SECURE_COOKIE=true
Secure cookies are transmitted only over HTTPS.
To investigate cookie-related problems, open your browser's Developer Tools and navigate to:
Application → Storage → Cookies
Inspect:
-
Laravel session cookie.
-
XSRF-TOKENcookie. -
Cookie domain.
-
Secure attribute.
-
SameSite attribute.
-
Expiration.
Then open the Network tab and verify that the expected cookies are included in the failing request.
Never share session cookies or CSRF tokens publicly.
5. Fix Laravel 419 Errors After Production Deployment
If your application works locally but returns 419 errors after deployment, compare the production environment with your local configuration.
Pay particular attention to these areas.
A. Verify APP_URL
Check your production .env:
APP_URL=https://yourdomain.com
Make sure it represents the intended application URL.
Remember that APP_URL alone does not determine session-cookie behaviour. Also inspect the actual request scheme and cookie configuration.
B. Verify APP_KEY consistency
Laravel uses its application encryption key to encrypt and decrypt data, including encrypted cookies.
Changing APP_KEY can invalidate existing encrypted cookies.
If your application runs on multiple servers, make sure the instances use a consistent application key.
Never generate a new production key simply to troubleshoot a 419 error.
C. Check HTTPS and reverse proxy configuration
Applications running behind Nginx, Cloudflare, or a load balancer may receive HTTPS requests from browsers while communicating with Laravel internally over HTTP.
If Laravel does not correctly recognize the original request scheme, cookie behaviour and generated URLs may be affected.
Review your trusted proxy configuration.
For Laravel 11 and 12, this is commonly configured through middleware in:
bootstrap/app.php
Trust only the appropriate proxy addresses or networks.
D. Check multiple application servers
If your application runs on multiple servers, verify that:
-
All instances use consistent application configuration.
-
The same
APP_KEYis used across instances. -
Session storage is shared where required.
-
Cookie configuration is consistent.
-
Load balancing does not direct requests to incompatible session stores.
For example, if Server A creates a file-based session and Server B receives the next request, Server B may not be able to retrieve that session.
A shared database or Redis session store is often more suitable for multi-server deployments.
6. Troubleshoot Laravel Sanctum and Livewire Authentication
Laravel Sanctum SPA authentication
Laravel Sanctum supports cookie-based authentication for first-party single-page applications.
Unlike API token authentication, SPA authentication uses Laravel's session-based authentication mechanism.
For example:
Frontend: http://localhost:3000
Backend: http://localhost:8000
Or in production:
Frontend: https://app.example.com
Backend: https://api.example.com
For first-party SPA authentication, the frontend and backend must share the same top-level domain.
Check the following configuration.
1. Stateful domains
In Laravel versions using config/sanctum.php, configure the frontend domains in the stateful setting.
For example:
SANCTUM_STATEFUL_DOMAINS=localhost:3000,127.0.0.1:8000,app.example.com
Use the actual frontend hostnames and ports.
2. Enable stateful API middleware
For Laravel 11 and 12 applications using the modern application structure, configure bootstrap/app.php:
use Illuminate\Foundation\Configuration\Middleware;
->withMiddleware(function (Middleware $middleware): void {
$middleware->statefulApi();
})
3. Configure CORS
If frontend and backend use different origins, enable credential support in your CORS configuration:
'supports_credentials' => true,
Also explicitly allow your frontend origin. Do not use a wildcard origin when credentialed requests are required.
4. Configure Axios
axios.defaults.withCredentials = true;
axios.defaults.withXSRFToken = true;
5. Initialize CSRF protection
Before login, request Laravel's CSRF cookie endpoint:
await axios.get('/sanctum/csrf-cookie');
After initialization, send the login request:
await axios.post('/login', {
email: 'user@example.com',
password: 'your-password'
});
If the browser does not send the expected session and XSRF cookies, authentication requests may fail.
Sanctum requires correctly configured cookies, CORS, stateful domains, and session handling. Setting only SANCTUM_STATEFUL_DOMAINS is not sufficient.
Livewire applications
Livewire handles its own AJAX communication, so you generally do not need to manually add CSRF headers to every Livewire request.
If Livewire returns a 419 error, investigate:
-
Session persistence.
-
Laravel session cookies.
-
Cookie domain and SameSite settings.
-
Expired sessions.
-
The failing Livewire request in browser Developer Tools.
For Livewire 3, the standard layout directives are:
<head>
@livewireStyles
</head>
<body>
@livewireScripts
</body>
If automatic asset injection is enabled, these directives may not be necessary.
Inspect the actual failed request rather than assuming missing JavaScript assets are responsible for every 419 error.
7. Debug Laravel 419 Errors and Handle CSRF Exceptions Safely
If the previous solutions do not resolve the issue, inspect the actual failing request instead of repeatedly changing configuration.
Check Laravel logs
Open:
storage/logs/laravel.log
To monitor recent log entries:
tail -f storage/logs/laravel.log
Look for session errors, encryption failures, and other exceptions around the time the request fails.
Remember that not every CSRF rejection automatically produces a detailed log entry.
Inspect the failed browser request
Open Developer Tools:
Network → Failed Request
Check the following:
| Item | What to investigate |
|---|---|
| Request method | POST, PUT, PATCH, or DELETE |
| Request URL | Correct domain and protocol |
| Status code | 419 |
| Request headers | Expected CSRF header |
| Request cookies | Laravel session cookie |
| Response body | Page Expired response |
This helps identify whether the issue originates from the token, session, cookies, or application configuration.
Configure CSRF exceptions safely
Sometimes external services, such as payment gateways, need to send webhook requests to your Laravel application without a browser-generated CSRF token.
In such cases, you can exclude specific routes from CSRF verification.
Laravel 11 and 12:
Configure the exception in bootstrap/app.php:
use Illuminate\Foundation\Configuration\Middleware;
->withMiddleware(function (Middleware $middleware): void {
$middleware->validateCsrfTokens(except: [
'webhook/payment',
]);
})
Laravel 10 and older applications:
Configure the exception in:
app/Http/Middleware/VerifyCsrfToken.php
Example:
protected $except = [
'webhook/payment',
];
Always verify the middleware configuration for your installed Laravel version before applying an example.
Security warning: Never disable CSRF protection globally simply to eliminate 419 errors. For external webhooks, implement the payment provider's signature verification or another appropriate authentication mechanism.
8. Laravel 419 Error Troubleshooting Checklist
Before making additional changes, work through this checklist.
Blade and frontend
-
Include
@csrfin state-changing Blade forms. -
Check the CSRF meta tag.
-
Verify Axios or Fetch API configuration.
-
Confirm the expected CSRF header is being sent.
Sessions and cookies
-
Verify
SESSION_DRIVER. -
Confirm session storage is available.
-
Review session lifetime.
-
Check cookie domain and expiration.
-
Verify HTTPS and secure-cookie settings.
Production environment
-
Verify
APP_URL. -
Check
APP_KEYconsistency. -
Review trusted proxy configuration.
-
Confirm shared session storage across application servers.
SPA and Livewire
-
Verify Sanctum stateful domains.
-
Enable stateful API middleware.
-
Configure credential-enabled CORS.
-
Initialize the Sanctum CSRF cookie.
-
Inspect failing Livewire requests.
Security and debugging
-
Inspect Laravel logs.
-
Examine the failed browser request.
-
Clear configuration cache only when necessary.
-
Verify CSRF exceptions.
-
Never disable CSRF protection globally as a workaround.
Frequently Asked Questions About Laravel 419 Errors
Why does Laravel show 419 Page Expired?
Laravel commonly returns a 419 response when its CSRF protection cannot validate a request against the current session. Typical causes include missing tokens, expired sessions, invalid cookies, and incorrect frontend/backend configuration.
How do I fix CSRF token mismatch in Laravel?
Start by checking whether your Blade form includes @csrf. For AJAX requests, verify that the correct CSRF header is sent. If the problem persists, inspect session storage, browser cookies, and domain configuration.
Why does Laravel CSRF work locally but fail in production?
Production environments may use different session drivers, cookie domains, HTTPS configurations, encryption keys, or reverse proxies. Compare local and production settings to identify the inconsistency.
Can I disable CSRF protection in Laravel?
Laravel allows specific routes to be excluded from CSRF verification, which may be necessary for external webhook endpoints. However, disabling CSRF protection globally is not recommended. Use appropriate alternative security mechanisms, such as webhook signature verification.
Conclusion
Laravel CSRF token mismatch errors are often caused by inconsistencies between the browser request, CSRF token, and session.
Start with the simplest checks: verify @csrf, inspect JavaScript request headers, and confirm that the browser sends the correct session cookies.
For more complex cases, investigate Sanctum configuration, production HTTPS settings, session storage, and reverse proxy behaviour.
The key is to identify why Laravel cannot validate the request rather than disabling the security mechanism to make the error disappear.