[Vuejs]-Dynamically add a route in a Nuxt3 middleware

0👍

If you insist on resolving method called before each route change, the Nuxt’s replacement for next() method you’re looking for is navigateTo
https://nuxt.com/docs/api/utils/navigate-to

And I advise you to use route middleware and put your logic into /middleware/routeGuard.global.ts. It will be auto-executed upon every route resolving event. The file will contain:

export default defineNuxtRouteMiddleware((to, from) => {

  // your route-resolving logic you wanna perform

  if ( /* navigation should happen */ {
    return navigateTo( /* your dynamic route */ )
  }
  // otherwise do nothing - code will flow and given to.path route will be resolved
})

EDIT: However, this would still need content inside /pages directory or some routes created via Vue Router. Because otherwise navigateTo will fail, as there would be no route to go.

Here is an example of one possible approach:

https://stackblitz.com/edit/github-8wz4sj

Based on pageType returned from API Nuxt route guard can dynamically re-route the original URL to a specific slug page.

-1👍

I suggest you use dynamic routing within /page directory structure – https://nuxt.com/docs/guide/directory-structure/pages#dynamic-routes

The [slug] concept is designed exactly for your usecase. You don’t need to know all possible routes in advance. You just provide a placeholder and Nuxt will take care of resolving during runtime.

Leave a comment