Nuxt 3 middleware infinite navigation guard

377 Views Asked by At

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

}
2

There are 2 best solutions below

1
On BEST ANSWER
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;
}
3
On

Try to use to.name instead from.name like this
if (to.name == 'id-create-issue' && from.name !== 'id-create-issue') {}
if (to.name !== 'id-create-issue') {}

as indicated in docs.