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

})


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!
Was this page helpful?