Introduction

Cross-Site Request Forgery (CSRF) protection is a critical security feature built into Laravel to prevent unauthorized actions on behalf of authenticated users. Laravel uses CSRF tokens to ensure that requests coming to your application are genuine and not forged by malicious third parties.

However, developers often encounter Laravel CSRF token mismatch errors, especially when working with APIs, AJAX calls, or modern frontend frameworks. These errors typically occur when the CSRF token is missing, expired, or improperly handled in requests.

If left unresolved, CSRF token mismatch issues can disrupt user sessions, cause unexpected logout problems, and break seamless communication between your frontend and Laravel API.

In this guide, we will explain why Laravel CSRF token mismatch errors happen frequently — particularly in Laravel 11 APIs — and show you how to fix them effectively. Whether you’re dealing with Laravel ajax csrf token mismatch, CSRF token mismatch Laravel API axios problems, or want to learn how to disable CSRF token in Laravel 11 for stateless APIs, this article covers everything you need to ensure smooth and secure API interactions.

What is CSRF Token Mismatch in Laravel?

Cross-Site Request Forgery (CSRF) is a security vulnerability that allows malicious websites to perform unauthorized actions on behalf of authenticated users without their knowledge. To protect against this, Laravel automatically generates a unique CSRF token for every active user session.

How Laravel Uses CSRF Tokens

Every time a user loads a page with a form or sends a POST, PUT, PATCH, or DELETE request, Laravel expects a valid CSRF token to be submitted alongside the request. This token acts as a secret key verifying that the request comes from the authenticated user and not a third party. Laravel then compares the submitted token with the token stored in the session. If they don’t match, Laravel rejects the request with a CSRF token mismatch error.

Why CSRF Token Mismatch Happens Frequently

You might frequently encounter Laravel CSRF token mismatch errors due to several reasons:

  • Missing Token in Request: If the CSRF token isn’t included in form submissions or AJAX requests, Laravel will refuse the request. This is common when making API calls or AJAX requests without attaching the token.
  • Expired Token: Laravel sessions and tokens have a lifetime. When tokens expire (due to session expiry or token TTL), any subsequent request with the old token results in a mismatch error.
  • Laravel 11 Specific Changes: In Laravel 11, some improvements and stricter middleware checks can cause token mismatches if tokens are not handled properly or API routes are not excluded from CSRF verification.
  • AJAX and SPA Requests: Frameworks that use JavaScript to make background requests (like Axios in Vue.js or React) need to manually include the CSRF token. Failing to do so leads to errors like Laravel ajax csrf token mismatch or CSRF token mismatch Laravel API axios.
  • Stateless APIs: API endpoints are usually stateless, meaning they don’t maintain session state and often don’t require CSRF protection. If CSRF is enabled for API routes, it can cause mismatches when the token isn’t sent.

Common Error Messages and Symptoms

Developers usually see one of the following when a CSRF token mismatch occurs:

  • “CSRF token mismatch” error displayed on submitting a form or making an API call
  • HTTP 419 Page Expired response from Laravel
  • Error logs or console messages like CSRF token mismatch Laravel API axios when making AJAX calls using Axios

Understanding these causes and recognizing these symptoms will help you diagnose and resolve Laravel CSRF token mismatch issues faster and more effectively.

Common Causes of Laravel CSRF Token Mismatch

1. Missing CSRF Token in Requests

Laravel requires the CSRF token to be included in all POST, PUT, PATCH, and DELETE requests. If you are using forms, ensure the token is added with the Blade directive:

<form method="POST" action="/submit">
@csrf
<!-- form inputs -->
</form>

For AJAX requests, the CSRF token must be sent explicitly. Include this meta tag in your HTML head:

<meta name="csrf-token" content="{{ csrf_token() }}">

Then, configure your JavaScript HTTP client to send the token. For example, with Axios:

axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

Without this, you’ll get a Laravel ajax csrf token mismatch error.


2. Expired or Invalid CSRF Token

CSRF tokens expire when the user session expires. By default, Laravel’s session lifetime is 120 minutes but can be configured in config/session.php:

'lifetime' => 120, // in minutes
'expire_on_close' => false,

If a user submits a request after the token expires, Laravel throws a CSRF token mismatch error.

Make sure your server time is synchronized (e.g., using NTP), and tokens are not cached in the browser or proxies, as stale tokens cause this issue.


3. CSRF Middleware Enabled on API Routes

API routes are typically stateless and do not require CSRF protection. By default, Laravel includes CSRF protection on web routes only, but if your API routes are inside the web middleware group or CSRF middleware applies to them, you will see mismatch errors.

To exclude API routes from CSRF verification, edit app/Http/Middleware/VerifyCsrfToken.php:

protected $except = [
'api/*',
];

This disables CSRF protection on all routes prefixed with api/, preventing Laravel api CSRF token mismatch errors.


4. Axios Not Sending Cookies or CSRF Token

When using Axios to send requests to your Laravel backend, ensure it sends cookies and CSRF tokens properly. Axios doesn’t send cookies by default on cross-origin requests. You must enable it:

axios.defaults.withCredentials = true;
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

Setting withCredentials to true ensures that cookies, including the XSRF-TOKEN cookie Laravel sets, are sent with each request.

Without this, you’ll encounter errors like CSRF token mismatch Laravel API axios.


5. Laravel XSRF-TOKEN Cookie Set as HttpOnly

Laravel stores the CSRF token in a cookie named XSRF-TOKEN. For JavaScript frameworks to read this cookie and send it with requests, the cookie cannot be set as HttpOnly.

Check your config/session.php:

'http_only' => false,

If this is set to true, JavaScript cannot read the token, leading to Laravel XSRF-TOKEN httponly issues.

Make sure the cookie is accessible to your JavaScript code so the CSRF token can be included in headers.

How to Fix Laravel CSRF Token Mismatch Errors

Fixing Laravel CSRF token mismatch errors depends on your application type — whether it’s a traditional web app, an API, or a single-page application using AJAX or Axios. Below are targeted solutions to common problems, including handling Laravel 11 specifics and Axios issues.


1. Ensure CSRF Token Is Present in All Requests (Web Apps & AJAX)

For Blade templates, always include the CSRF token in your forms:

<form method="POST" action="/submit">
@csrf
<!-- form inputs -->
</form>

Add this meta tag inside your HTML <head>:

<meta name="csrf-token" content="{{ csrf_token() }}">

For AJAX requests, configure your JavaScript HTTP client to include the CSRF token:

// For Axios
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

This addresses the common Laravel ajax csrf token mismatch problem.


2. Disable CSRF Verification for API Routes (Laravel 11)

Since APIs are usually stateless, you should exclude API routes from CSRF protection. Open app/Http/Middleware/VerifyCsrfToken.php and add your API routes to the $except array:

protected $except = [
'api/*',
];

This step is critical to avoid Laravel api CSRF token mismatch errors when using token-based API authentication.


3. Configure Axios to Send Cookies and Tokens Properly

When using Axios with Laravel APIs, ensure that Axios sends cookies (like the XSRF-TOKEN cookie) by setting:

axios.defaults.withCredentials = true;
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

Without withCredentials: true, your API requests won’t include cookies, resulting in CSRF token mismatch Laravel API axios errors.


4. Adjust Session and Token Lifetimes to Prevent Expiry Issues

In config/session.php, increase the session lifetime if users experience token expiry too soon:

'lifetime' => 120, // minutes, adjust as needed
'expire_on_close' => false,

Make sure your server time is synchronized to avoid token TTL mismatches.


5. Ensure XSRF-TOKEN Cookie is Accessible to JavaScript

In config/session.php, confirm that the http_only flag is set to false if your frontend needs to read the CSRF token from cookies:

'http_only' => false,

This prevents the Laravel XSRF-TOKEN httponly issue where JavaScript cannot access the CSRF token cookie.


6. Clear Browser Cache and Local Storage on Login

Old or stale tokens stored in the browser can cause CSRF mismatch errors. After login or token refresh, clear the browser’s cache and local storage to ensure the frontend uses fresh tokens.


Bonus: Disable CSRF Protection (Only If Absolutely Necessary)

If you want to disable CSRF token in Laravel 11 completely for certain routes (not recommended for web forms), you can exclude them as shown:

protected $except = [
'api/*',
'some/custom/route',
];

But avoid disabling CSRF protection on routes handling sensitive user data or forms.

Session & Token Expiry Issues Related to CSRF Tokens

CSRF tokens in Laravel are tightly linked to the user session, meaning that when the session expires or is invalidated, the CSRF token also becomes invalid. This is a common cause of unexpected Laravel CSRF token mismatch errors, particularly in API-driven apps or single-page applications (SPAs). Understanding how session and token lifetimes interact helps avoid these issues.


How Laravel Manages Sessions and CSRF Tokens

Laravel generates a unique CSRF token per user session. This token is stored server-side in the session and also shared with the client through a cookie (commonly the XSRF-TOKEN cookie) or embedded in forms. When the client sends a request, Laravel compares the submitted token with the stored session token.

If the session expires, the stored token is lost, and any subsequent request carrying the old token triggers a mismatch error.


Default Session Lifetime and Its Impact

By default, Laravel sets session lifetime in minutes in config/session.php:

'lifetime' => 120,   // 2 hours
'expire_on_close' => false,
  • lifetime: Determines how long the session remains valid without user activity.
  • expire_on_close: When true, sessions expire as soon as the browser closes.

A short session lifetime or expire_on_close set to true causes tokens to expire quickly, leading to Laravel login session expiring quickly issues and CSRF mismatches.


How to Extend Session Lifetime to Reduce Token Expiry Errors

Increasing session lifetime allows users to stay logged in longer, reducing the chance of CSRF token expiry mid-session. For example, to extend sessions to 4 hours:

// config/session.php
'lifetime' => 240, // 4 hours
'expire_on_close' => false,

This change is especially important for SPAs or long-lived forms where users might be idle before submitting requests.


Synchronizing Server Time to Prevent Immediate Expiry

Token expiration is time-sensitive. If your server clock is out of sync with the client, tokens may appear expired immediately after being issued, leading to token mismatch or “token expired” errors right after login.

To avoid this:

  • Ensure the server’s system clock is synchronized with NTP (Network Time Protocol).
  • Check the timezone configuration in Laravel (config/app.php) matches your server’s timezone.
  • Verify that JWT token TTLs and Passport token expiration settings use the correct server time.

Handling Token Expiry in Laravel Passport and JWT

When using token-based authentication:

  • Laravel Passport allows you to configure token and refresh token expiration:
use Laravel\Passport\Passport;

Passport::tokensExpireIn(now()->addMinutes(60)); // Access tokens valid for 1 hour
Passport::refreshTokensExpireIn(now()->addDays(15)); // Refresh tokens valid for 15 days
  • JWT (tymon/jwt-auth) uses a TTL setting in minutes inside config/jwt.php:
'ttl' => 60,  // Tokens expire after 60 minutes

Tokens expire after this TTL, and requests using expired tokens will fail with 401 errors unless refresh tokens or re-authentication are used.


Clearing Stale Tokens After Login or Refresh

Old tokens stored in browser local storage, cookies, or session storage can cause immediate CSRF token mismatch or authentication failures. Always clear these tokens on login or logout:

// Clear localStorage on login/logout
localStorage.removeItem('auth_token');
localStorage.removeItem('refresh_token');

Also, consider implementing an auto-refresh mechanism that requests a new token when the current one expires, improving user experience.


Best Practices for Session & Token Expiry

  • Set appropriate session.lifetime and expire_on_close values for your app’s needs.
  • Synchronize server time to avoid premature token expiry.
  • Use token expiry configurations in Passport or JWT properly.
  • Clear stale tokens on login and logout to avoid reusing invalid tokens.
  • Implement token refresh mechanisms on the frontend.

Handling CSRF Token Mismatch with Axios in Laravel APIs

Using Axios to make API requests in Laravel-powered applications is common, but improperly configured Axios requests often trigger CSRF token mismatch Laravel API axios errors. Proper handling of CSRF tokens and cookies in Axios is critical for secure and smooth frontend-backend communication.


Why Axios Causes CSRF Token Mismatch Errors

Axios, by default, does not send cookies or custom headers unless explicitly configured. Since Laravel relies on the XSRF-TOKEN cookie or CSRF token headers for verification, failing to send these results in mismatch errors.


Step 1: Include CSRF Token Meta Tag in Your HTML

Make sure your main HTML page includes the CSRF token meta tag, which Axios will use:

<meta name="csrf-token" content="{{ csrf_token() }}">

Step 2: Configure Axios to Send CSRF Token and Cookies

Set Axios defaults to include the CSRF token in headers and to send cookies with every request:

import axios from 'axios';

// Set the CSRF token from meta tag as a default header
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

// Ensure cookies are sent with requests (important for Laravel session and XSRF-TOKEN cookie)
axios.defaults.withCredentials = true;

This configuration ensures that:

  • The X-CSRF-TOKEN header is included in every request
  • Cookies like XSRF-TOKEN are sent, allowing Laravel to verify the request origin

Step 3: Handling Cross-Origin Requests (CORS)

If your frontend and backend are served from different domains or ports, configure CORS in Laravel (app/Http/Middleware/HandleCors.php or config/cors.php) to allow credentials:

'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['https://your-frontend-domain.com'],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,

Without supports_credentials set to true, browsers won’t send cookies on cross-origin requests, causing CSRF token mismatch errors.


Step 4: Use Laravel Sanctum’s CSRF Cookie Endpoint (For SPAs)

If you’re using Laravel Sanctum for SPA authentication, call the /sanctum/csrf-cookie endpoint before making authenticated requests. This sets the XSRF-TOKEN cookie needed by Laravel:

axios.get('/sanctum/csrf-cookie').then(response => {
// Now make your authenticated API requests
axios.post('/api/user', { /* data */ });
});

Step 5: Debugging Tips for Axios CSRF Issues

  • Inspect browser dev tools to confirm that the XSRF-TOKEN cookie is present and not marked HttpOnly.
  • Verify Axios requests include the X-CSRF-TOKEN header and cookies.
  • Check Laravel logs for CSRF token mismatch errors and verify the token Laravel expects vs. what’s sent.

By following these steps, you can eliminate CSRF token mismatch Laravel API axios errors and secure your Laravel API endpoints when communicating via Axios.

Additional Tips and Best Practices

To maintain a secure and seamless Laravel application, especially when dealing with CSRF tokens and API authentication, follow these additional best practices:


1. Clear Browser Cache and Local Storage After Login or Logout

Old CSRF tokens and authentication tokens stored in browser cache or local storage can cause persistent CSRF token mismatch errors. Always clear these on login/logout:

localStorage.clear();
sessionStorage.clear();

This ensures your frontend always uses fresh tokens, preventing stale token errors.


2. Use Persistent Cookies for Longer Sessions

Set persistent cookies to maintain sessions beyond browser closures. In config/session.php, set:

'expire_on_close' => false,

This avoids quick session expiration and CSRF token invalidation, especially important for SPAs.


3. Avoid Running php artisan config:cache Without Clearing Cache

If you make changes to config/session.php or VerifyCsrfToken.php, always clear and refresh your config cache:

php artisan config:clear
php artisan cache:clear
php artisan config:cache

Failing to do so may cause Laravel to use outdated configurations, leading to unexpected token mismatch errors.


4. Sync Server Time and Timezone Settings

Ensure your server time is synchronized (using NTP) and Laravel’s timezone (config/app.php) matches your server’s timezone to prevent token expiry issues.


5. Monitor and Purge Expired Tokens and Sessions

For applications using Passport or Sanctum, regularly clear expired tokens and sessions to improve performance and avoid confusion from stale tokens:

php artisan passport:purge

6. Secure Logout Logic to Prevent Errors on Expired Sessions

When logging out, check if the user is authenticated before calling logout to avoid errors:

public function logout(Request $request)
{
if (Auth::check()) {
Auth::logout();
}
return response()->json(['message' => 'Logged out successfully']);
}

7. Always Use Token-Based Authentication for APIs

Avoid session-based authentication for APIs. Use Laravel Sanctum, Passport, or JWT to implement token-based authentication that’s stateless and more secure.


8. Handle Token Expiration Gracefully

Implement frontend logic to catch 401 errors due to expired tokens and refresh tokens automatically or redirect users to login.


Following these tips will help you avoid common pitfalls related to Laravel CSRF token mismatch and session expiration, making your API integration smooth and secure.

Frequently Asked Questions (FAQs)

How to disable CSRF token in Laravel 11?

To disable CSRF protection for specific routes or APIs in Laravel 11, add them to the $except array in app/Http/Middleware/VerifyCsrfToken.php:

protected $except = [
'api/*',
];

This prevents Laravel from checking CSRF tokens on these routes, useful for stateless API endpoints.


Why do I get Laravel API CSRF token mismatch errors with Axios?

Axios requests must send the CSRF token and cookies properly. Configure Axios like this:

axios.defaults.withCredentials = true;
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

Without this setup, Laravel will reject the request with a CSRF token mismatch error.


How do I fix Laravel ajax CSRF token mismatch errors?

Ensure your AJAX requests include the CSRF token, usually by adding it to request headers or including it in form data. Also, include the CSRF meta tag in your HTML:

<meta name="csrf-token" content="{{ csrf_token() }}">

What is Laravel XSRF-TOKEN httponly and why does it cause issues?

The XSRF-TOKEN cookie stores the CSRF token for JavaScript to read. If it is set with the HttpOnly flag, JavaScript cannot access it, leading to token mismatch errors. In config/session.php, set:

'http_only' => false,

to allow JavaScript access.


Why does my Laravel 11 CSRF token mismatch error keep happening?

This can be due to expired tokens, incorrect Axios setup, CSRF middleware applying to APIs, or server time desynchronization. Follow best practices like disabling CSRF for APIs, configuring Axios properly, extending session lifetime, and syncing server time.

Conclusion

CSRF token mismatch errors in Laravel can be a major roadblock when building secure and user-friendly APIs or web applications. Whether you encounter Laravel CSRF token mismatch in traditional forms, AJAX requests, or modern SPA APIs using Axios, understanding the root causes is key to fixing the problem.

In Laravel 11 and beyond, properly handling CSRF tokens involves:

  • Including tokens in all form submissions and AJAX requests
  • Disabling CSRF verification for stateless API routes
  • Configuring Axios to send CSRF tokens and cookies correctly
  • Extending session lifetimes to prevent premature token expiry
  • Avoiding HttpOnly flags on the XSRF-TOKEN cookie for JavaScript accessibility

By following these best practices, you can eliminate Laravel api CSRF token mismatch, Laravel ajax csrf token mismatch, and related errors, ensuring smooth frontend-backend communication and enhanced security.

If you run into issues or need assistance with how to disable CSRF token in Laravel 11 or fixing CSRF token mismatch Laravel API axios errors, feel free to reach out or leave a comment. We’re here to help you build robust Laravel applications with confidence.

External Resource Links for Reference

To deepen your understanding and explore official documentation and community resources on CSRF token handling and session management in Laravel, check out these helpful links:

These resources offer in-depth insights and practical solutions to common challenges involving CSRF tokens, API authentication, and session expiry in Laravel.

Categorized in: