How to catch 401 from server routes and redirect to login page

I have a nuxt 3 app that uses SSR and server routes, it's using a terrible auth solution that I built, it's just a simple session token, but when my session token is invalidated, I get stuck on a 401 page until I delete my sessionToken cookie and refresh, this is because my middleware doesnt look for 401 errors, it only check if the cookie exists:
// middleware/auth.ts
export default defineNuxtRouteMiddleware(() => {
if (!useCookie('sessionToken').value) {
return navigateTo('/login');
}
});
// middleware/auth.ts
export default defineNuxtRouteMiddleware(() => {
if (!useCookie('sessionToken').value) {
return navigateTo('/login');
}
});
How should I redirect a user to the login page if their session token is invalid or doesnt exist?
1 Reply
TokyoStarz
TokyoStarzOP2y ago
maybe this:
export default defineNuxtRouteMiddleware(() => {
if (useError().value?.message.trim().split(' ')[0]?.slice(1,4) == '401') return navigateTo('/login');
if (!useCookie('sessionToken').value) {
return navigateTo('/login');
}
});
export default defineNuxtRouteMiddleware(() => {
if (useError().value?.message.trim().split(' ')[0]?.slice(1,4) == '401') return navigateTo('/login');
if (!useCookie('sessionToken').value) {
return navigateTo('/login');
}
});
it works when I reload the page (getting a straight 401 from the server because SSR) but if my session gets invalidated then I try to navigate to something that uses auth I get an error from the api but I don't get redirected to the login page
Want results from more Discord servers?
Add your server