How I am reproducing this error: Open Inspect => Application => storage => delete cookies
When I delete cookies and click on any of the links on the application, the request will receive a 401 response but the app won't be redirected to the login page. So, I have added the following code to my HTTP client.
client.interceptors.response.use(null, (error) => {
//added code
if (error.response.status === 401) {
window.location.href = "/";
}
return Promise.reject(error);
});
This will redirect the user to the login page, but instantly it will redirect the user to the dashboard, and again on the dashboard request it will receive 401, then again it will forward the user to the / page, in this way it is sticking in the login page.
My login.jsx
export default function Login() {
...
const { login } = useAuth({
middleware: 'guest',
redirectIfAuthenticated: '/dashboard'
})
...
...
...
}
and, useAuth hook:
export const useAuth = ({middleware, redirectIfAuthenticated} = {}) => {
let navigate = useNavigate();
let params = useParams();
const {data: user, error, mutate} = useSWR('/api/user', () =>
httpClient
.get('/api/user')
.then(res => res.data)
.catch(error => {
if (error.response.status !== 409) throw error
// mutate('/verify-email')
}),
{
revalidateIfStale: false,
revalidateOnFocus: false
}
)
useEffect(() => {
if (middleware === 'guest' && redirectIfAuthenticated && user) navigate(redirectIfAuthenticated)
if (middleware === 'auth' && error) logout()
}, [user, error])
return {
user
}
}