NuxtN
Nuxt3y ago
Zoe

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');
    }
});

How should I redirect a user to the login page if their session token is invalid or doesnt exist?
Was this page helpful?