Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Daaf's avatar
Level 10

Handle TokenMismatchException in Vue

I am using Laravel + Vue + Vue Router.

How to you handle the TokenMismatchException in Vue after the XSRF-token expired? How to you reset the token after it expired?

Should I use an interceptor and redirect to refresh the page and redirect to login?

axios.interceptors.response.use(function (response) {
    return response
}, function (error) {
    if (Cookies.get('XSRF-TOKEN') === undefined) {
        window.location = '/login';

        return Promise.reject('')
    }
})

Or is it possible to have the interceptor rather request a new XSRF-token from an endpoint (www.mysite.com/token) so that the page does not need to be refreshed? How would you do this?

axios.interceptors.response.use(function (response) {
    return response
}, function (error) {

    console.log(Cookies.get('XSRF-TOKEN') === undefined)

    if (Cookies.get('XSRF-TOKEN') === undefined) {
        axios.get('/token')
            .then(response => {
        /// Do something?
            })


        return Promise.reject('')
    }

})

Is there another way?

0 likes
3 replies
Abi's avatar
Abi
Best Answer
Level 24

@daaf add this to the bootstrap.js

window.axios = require('axios');

window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN': window.Laravel.csrfToken,
    'X-Requested-With': 'XMLHttpRequest'
};

and this to your layout page

  <script type="text/javascript">
            window.Laravel = {
                csrfToken : "<?= csrf_token();  ?>"
            };



        </script>
3 likes
Daaf's avatar
Level 10

It seems to work, thanks. But I don't understand why...

So what happens when the token expires?

Please or to participate in this conversation.