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

bradders's avatar

Detecting Expired Session with Sanctum/SPA

I've got a front-end application built in NextJS that uses axios to consume a Laravel API (using sanctum for auth). Login/Register/Logout is all working as expected, but I'm wondering how to deal with an expired session.

Currently my UI still thinks it has a valid user session, but any subsequent API calls don't authenticate as the session has expired. Should I be checking for a 401 response and manually logged the user out, or is there a cleaner way?

Thanks!

0 likes
3 replies
fylzero's avatar
fylzero
Best Answer
Level 67

@bradders You'll want to use an Axios interceptor for this... it will detect a session expiration then send the user to log back in instead of just wonking out and sitting there.

window.axios.interceptors.response.use(
    function(response) {
        // Call was successful, don't do anything special.
        return response;
    },
    function (error) {
    switch (error.response.status) {
        case 401: // Not logged in
        case 419: // Session expired
        case 503: // Down for maintenance
            // Bounce the user to the login screen with a redirect back
            window.location.reload();
            break;
        case 500:
            alert('Oops, something went wrong!  The team have been notified.');
            break;
        default:
            // Allow individual requests to handle other errors
            return Promise.reject(error);
    }
});

Also, you should bump your session timeout in your env to whatever is good for you. Typical practice is to set it to like 30 days now.

Jess Archer explains in this video... https://youtu.be/Zv4bUXEwl20?t=717

SESSION_LIFETIME=43200 # 30 Days

5 likes
Benounnas Oussama's avatar

thank you, i was having the same issue and looking for a fix, i guess this one of the cons using sessions in SPA, what do you think @fylzero , statefull or stateless is better ?

bradders's avatar

Awesome, thanks for that! Appreciate the video link too, watched the whole thing! :)

1 like

Please or to participate in this conversation.