Mokta's avatar
Level 2

Laravel Sanctum SPA - User Lifecycle (Client Side)

Hey all,

I'm using VueJS on the same domain as my Laravel Application. I can successfully log a user in without any problems, but don't know the best way to check if a user is still logged in.

I wanted to see if anyone has any advice regarding handling a users session once a user logs in / if this is handled automatically when I call the API?

I can think of a few ways, to do this such as:

  1. Create a new cookie indicating the user has logged in and set it to expire before the existing Laravel cookies, forcing the user to re-login.

  2. For any 401 results (unauthenticated) prompt the user to log in again. Redirect the user back to the same page they were using and perhaps force them to resubmit the data again.

  3. Every x minutes, attempt to refresh the existing cookies with Laravel, hopefully preventing a 401 response from occurring.

  4. A combination of the above.

Not certain if there are any other options.

Use Cases

  1. User closes and reopens the website.
  2. User leaves website open and comes back in x minutes after cookie has expired.
  3. User is continuously using website and when attempting to hit API method, they get a 401.

Any advice would be appreciated

0 likes
2 replies
davidifranco's avatar
Level 10

If your using Axios you could use Axios Interceptors to catch any 401 response codes and redirect the user to the login page.

In your bootstrap.js or app.js file

axios.interceptors.response.use(function (response) {
    return response;
    }, function (error) {
    if(error.response.status === 401) {
        // redirect to login page
        window.location.href = "/login";
    }
    return Promise.reject(error);
  });
1 like
Mokta's avatar
Level 2

Awesome, wasn't aware of axios interceptors. I'll definitely implement that as a catch all solution.

Please or to participate in this conversation.