N
Nuxt2y ago
Thr0nSK

Dynamically added route at runtime

Hi, I'm trying to dynamically add a route at runtime, however, the solution below seems to add the route only after it's already resolved (?)
export default defineNuxtPlugin(nuxtApp => {

const router = useRouter()

addRouteMiddleware('routing', async (to) => {
if (to.path == '/my-awesome-product') {
router.addRoute({
component: () => import('/pages/product.vue'),
name: 'product',
path: to.path
})
}

}, { global: true })

})
export default defineNuxtPlugin(nuxtApp => {

const router = useRouter()

addRouteMiddleware('routing', async (to) => {
if (to.path == '/my-awesome-product') {
router.addRoute({
component: () => import('/pages/product.vue'),
name: 'product',
path: to.path
})
}

}, { global: true })

})
When I navigate directly to /my-awesome-product, I get a 404 but if I continue to use the site without reloading (so that the route stays in the local vue router), the next navigation to /my-awesome-product works fine. Any idea what I'm doing wrong? Thanks!
1 Reply
Thr0nSK
Thr0nSKOP2y ago
I also tried returning to.fullPath to cause a redirect but that seems to create an infinite redirect loop seems like router.hasRoute(‘/my-awesome-product’) returns true right after the route is added.. so the route should be there before the middlware returns… I found something about calling next() in vue router but can’t figure out how to do it in a Nuxt3 middleware
Want results from more Discord servers?
Add your server