Nuxt3 "await navigateTo ('/some-path')" not work first time call inside "defineNuxtRouteMiddleware", but working well at least a declare from outside
Asked Answered
S

3

5
export default defineNuxtRouteMiddleware(async(to, from) => {
    const loggedIn = useState('loggedIn', () => false)
    if(loggedIn.value == false) {
        if(to.path == '/auth/login') {
            await navigateTo(to.path)
        }else if(to.path == '/') {
            await navigateTo('/auth/login')
        }else if(!(to.path == '/auth/login') or !(to.path == '/')) {
            //return abortNavigation()
            await navigateTo('/auth/login')
        }else {
            return abortNavigation()
        }
    }else {
        console.log('to:', to.path)
        console.log('from:', from.path)
        await navigateTo(to.path)
    }
})

The problem is "await navigateTo('/auth/login')" not working of above code in the below lines if I browse to ".../dashboard", but work fine when any of the page at least have a "await navigateTo('/dashboard')". It work also fine for "return abortNavigation"

---
"else if(!(to.path == '/auth/login') or !(to.path == '/')) { 
    await navigateTo('/auth/login') 
}"
---

But I want without calling first time "await navigateTo('/dashboard')" from any of the page it should work.

Sporophore answered 2/3, 2023 at 5:5 Comment(0)
I
6

Try using return instead of await while calling navigateTo, you can find an example in the documentation: https://nuxt.com/docs/api/utils/navigate-to.

export default defineNuxtRouteMiddleware((to, from) => {
  // setting the redirect code to '301 Moved Permanently'
  return navigateTo('/search', { redirectCode: 301 })
})

If you call a funcion inside the middleware that redirects the user in case of errors, make sure to return navigateTo back up to the middleware caller.

Inspiration answered 31/3, 2023 at 8:17 Comment(0)
P
1

you can use a propert external as true, this will open the tab like if was a new tab,with that the page will load correctly.

navigateTo('/login', { external: true})

in the case of the auth middleware it is works well.

Prostitution answered 31/8, 2023 at 20:37 Comment(1)
external in not a _blank and can't open new tabLamentation
I
-1

I've had a similar issue with navigateTo not working in an async middleware. The workaround that worked for me is to use:

const app = useNuxtApp()
return callWithNuxt(app, () => navigateTo('/your/path'))
Ilario answered 15/3, 2023 at 14:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.