Search code examples
laravelvue.jscsrfcsrf-token

Laravel + Vue.js (axios) - CSRF token mismatch


I have problem with csrf token in Laravel. Sometimes request POST (via axios) returns 419 code "CSRF token mismatch" but request header contain CSRF and XSRF tokens. Interestingly, it's not happend in incognito mode.

enter image description here

App.blade:

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

bootstrap.js:

window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';


let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

Kernel.php:

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\Localization::class,
        ],

I tried to clear cache and config with no results. Any ideas how to fix it?


Solution

  • Sometimes?! It sounds like a expired token.

    When you're working in incognito tabs, you have a fresh token.

    Try location.reload() when you're getting 419 error code and everything goes well.