nuxt.jsvuejs3middlewarenuxtjs3nuxt-middleware

Nuxt 3 middleware infinite navigation guard


I've created auth.global.ts

Detected a possibly infinite redirection in a navigation guard when going from "/auth/login" to "/34/create-issue". Aborting to avoid a Stack Overflow. Are you always returning a new location within a navigation guard? That would lead to this error. Only return when redirecting or aborting, that should fix this. This might break in production if not fixed.

export default defineNuxtRouteMiddleware(async (to, from) => {
    let authStore = useAuthStore()
    let { isLoggedIn } = authStore
    const token = useCookie('token')

    if (to.name == 'id-create-issue' && from.name !== 'id-create-issue') {
        return navigateTo(to.path, { replace: true })
    }

    if (isLoggedIn && to.path === '/auth/login') {
        return navigateTo('/company')
     }

     if (!token.value && to.path !== '/auth/login') {
        return navigateTo('/auth/login', { replace: true })
     }

}

Solution

  • if (to.name == 'id-create-issue' && to.path !== from.path) {
        if(from.path !== to.path) {return}
        return navigateTo(to.path, { replace: false });
    }
    

    Check from.path and to.path; if they are the same, then return nothing. This will prevent an infinite loop.

    You can also disable middleware for this specific route by:

    if (to.name == 'id-create-issue') {
         return;
    }