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

sndytj's avatar

Detect PHP session end with Vue

I'm using vue in some blade files, the problem is that when the session's lifetime ends and I make AJAX requests with a Vue component, how could I detect that type of error and redirect to the login screen or display a message?

0 likes
1 reply
bobbybouwmann's avatar
Level 88

When you use axios for example for your requests you can use interceptors to check for any 401 Unauthorized responses. Whenever you get a 401 Unauthorized you should be redirected to the login page. Your setup might look like this

const api = axios.create({
  baseURL: `${config.host}`,
  timeout: 10000,
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/json',
  },
  responseType: 'json'
});

api.interceptors.request.use((config) => {
  config.headers.Authorization = `Bearer ${auth.getToken()}`;

  return config;
}, error => Promise.reject(error));

api.interceptors.response.use(response => response, (error) => {
  const statusCode = error.response.status

  if (statusCode === 401) {
    auth.deleteToken();

    routes.push({ name: 'login' });

    return Promise.reject(error);
  }
});

Well this is the basic gist of it! Note that I'm using the vue-router here as well. So the only thing you need to do is make sure that your api return a response with 401 ;)

Please or to participate in this conversation.