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

peterlc's avatar

Check Laravel login session

Hi,

I want my Vue router to redirect me if the Laravel login session is expired.

Right now i have this 401 code in my store action:

   getCustomersIndexData: ({commit, state}) => {
        axios.get('/admin/customer/customersApi', {
            params: state.customersfilter
        }).then(response => {
            commit('SET_CUSTOMERS_LIST', response.data);
        }).catch((error) => {
            // check if unauthorized error returned
            if (error.response.status === 401) {
                window.location = "/login";
            }
        });
    },

This is not optimal i guess and i would like this 401 code in the rout somehow redirecting user as soon as session expired and user clicks again.

0 likes
10 replies
jurjen's avatar

You could register a global before guard on your router.

router.beforeEach((to, from, next) => {
    if (someSessionExpiredCheckHere) { 
        next({
            path: '/login',
            query: { return: to.fullPath } // can be used to redirect the user back to the requested page after logging in
        })
    }
    next()
})
peterlc's avatar

Thank you @jurjen

Feel so stupid now but i have to ask where should i put this code of yours, in what file?

peterlc's avatar

Any tip on what to replace "someSessionExpiredCheckHere" wkth @jurjen ?

jurjen's avatar

You can put this in the file where you init your router.

Not sure what's the best way to check if the session has expired. If you know the duration of the session you could perhaps store this value in your vuex store and create an action that returns wether or not the session has expired. From your beforeEach you can then call this action.

Something like:

router.beforeEach((to, from, next) => {
    if (router.app.$store.dispatch('sessionHasExpired')) { 
        next({
            path: '/login',
            query: { return: to.fullPath }
        })
    }
    next()
})
Connor-S-Parks's avatar
Level 8

Why not just do something like this?

Vue.http.interceptors.push({
  response(resp) {
    // Check if the user is no longer signed in,
    // if so then we need them to sign back in.
    if (resp.status === 401) {
      window.location.href = '/sign-in';

      return;
    }

    return resp;
  }
});

If you want it to continually check at an interval then you can do something as simple as this:

setInterval(() => Vue.$http.get('/api/ping'), 2500);

It is worth noting that if you do this then you may want to elaborate to avoid fighting redirections...

Vue.http.interceptors.push({
  response(resp) {
    // Check if the user is no longer signed in,
    // if so then we need them to sign back in.
    if (resp.status === 401) {
      clearInterval(window.pinger);

      window.location.href = '/sign-in';

      return;
    }

    return resp;
  }
});

window.pinger = setInterval(() => Vue.$http.get('/api/ping'), 2500);
1 like
peterlc's avatar

Thank you @Connor-S-Parks this is exactly what im looking for.

Please tell me where to put it though.

I tried in my main js file like so:

import SelectSingleSearch from './components/general/Select/SelectSingleSearch.vue'
Vue.component('select-single-search', SelectSingleSearch);

import Toast from './components/general/Toast/Toast.vue'
Vue.component('toast', Toast);

import DiHeader from './components/general/Header/DiHeader.vue';
import Customers from './components/customers/Customers.vue';

Vue.prototype.trans = (key) => {
    return _.get(window.trans, key, key);
};

import router from './routes/router';

Vue.http.interceptors.push({
    response(resp) {
        // Check if the user is no longer signed in,
        // if so then we need them to sign back in.
        if (resp.status === 401) {
            window.location.href = '/login';

            return;
        }

        return resp;
    }
});

import { store } from './store/store';

const customers = new Vue({
    el: '#customers',
    router,
    store,
    components: {
        DiHeader,
        Customers
    }
});

but i get

Uncaught TypeError: Cannot read property 'interceptors' of undefined
    at Object.defineProperty.value (customers.3591766….js:21832)
    at __webpack_require__ (customers.3591766….js:20)
    at Object.<anonymous> (customers.3591766….js:29977)
    at __webpack_require__ (customers.3591766….js:20)
    at customers.3591766….js:66
    at customers.3591766….js:69

in my console

peterlc's avatar

Well it turned out i cant use:

Vue.http.interceptors.push({
    response(resp) {

since i dont use vue-resource.

I use Axios and this is the way to do it :)


axios.interceptors.response.use((response) => {
    console.log(response.status);
        // Check if the user is no longer signed in,
        // if so then we need them to sign back in.
        if (response.status === 401) {
            window.location.href = '/login';

            return;
        }

        return response;

});

Thank you everyone :)

3 likes
Connor-S-Parks's avatar

This requires that you have a Vue.$http binding, such as VueResource. Apologies for nto mentioning that.

Please or to participate in this conversation.