Implement auto logout function in react and laravel

58 Views Asked by At

I'm creating a project so in my project it generates token and i use laravel sanctum for this so i want to when the token is expired i want to log it out automatically and navigate to my login page again how will i do that were will i put my auto logout function is it in the login.jsx file, RequireAuth.jsx, or in my axios file? this is the file i have in my project mainly

This is my AuthController code

 $remember_token = $user->createToken('remember_token',expiresAt:now()->addMinute())->plainTextToken;

This is my Login.jsx

   const onSubmit = async (data, event) => {
   event.preventDefault(); // Prevent default form submission behavior
   setLoading(true);
   await csrf()
     try {
     const config = {
    headers: {
      "Content-type": "application/json",
    }
  };
  const postData = {
    email_address: data.email_address,
    password: data.password,
  };
  const response = await axios.post(
    LOGIN_URL,
    JSON.stringify(postData),
    config
  ); 

  const { remember_token, user, roles_name } = response.data;
  console.log(JSON.stringify(response?.data));
  
  const role_id = response?.data?.user?.role_id;

  setLoading(false);

  // Set the authenticated user state using setAuth from your useAuth hook
  setAuth({ user, remember_token, roles_name, role_id});

  const rolePath = role_id === 1  ? '/'  : role_id === 2 ? '/' : role_id === 3 ? 
  '/scholar-dashboard' : '/login';

  // Navigate the user to the intended route (from variable contains the intended route)
  navigate(rolePath);
  
} catch (err) {
  setLoading(false);
  if(err.response?.status === 422){
    setErrMsg('Email address and password are required');
  }
  else if(err.response?.status === 409){
    setErrMsg('Email Address already been taken');
  }
  else if(err.response?.status === 500){
    setErrMsg('Server Error');
  }
  else if (err.response?.status === 401) {
    setErrMsg('Login failed. Please check your credentials and try again.');
  }
  else{
    setErrMsg('Network error occurred. Please try again.');
  }
}

}

1

There are 1 best solutions below

0
ajay pediredla On

Create a file where you configure your Axios instance. You can include an interceptor that checks the response for token expiration and logs the user out.

Example (axiosConfig.js):

import axios from 'axios';
import { logout } from './auth';

const api = axios.create({
  baseURL: 'your_api_base_url',
 });

// Add a response interceptor
api.interceptors.response.use(
 (response) => response,
 (error) => {
// Check if the error is due to an expired token
if (error.response && error.response.status === 401) {
  // Log out the user when the token is expired
  logout();
  // You can also navigate to the login page here
  // Example: window.location.href = '/login';
}
return Promise.reject(error);
}
);

export default api;

This way, you centralize the logout logic in the Axios configuration, making it easier to manage and maintain. When the token expires, any request made using Axios will trigger the interceptor, leading to the automatic logout.