How to assign a middleware to custom routes?

So for file-system based routing you assign middleware to individual pages or a parent page through definePageMeta utility function. But, as definePageMeta is ignored in custom routing, how do you assign a middleware in this case. I have gone through the documentation but couldn't find any clean solutions. I think you should be able to assign middleware to routes in router.options.js file like this:
{
path: "account",
name: "account",
middleware: "auth",
component: account
}
{
path: "account",
name: "account",
middleware: "auth",
component: account
}
But this doesn't work. Do you have any better solution for this?
3 Replies
Ragura
Ragura6mo ago
You can add middleware programmatically with the pages:extend hook. https://nuxt.com/docs/guide/directory-structure/middleware#setting-middleware-at-build-time This usage is specifically called out with custom routing here: https://nuxt.com/docs/guide/recipes/custom-routing#router-config
Nuxt
Custom Routing · Recipes
In Nuxt 3, your routing is defined by the structure of your files inside the pages directory. However, since it uses vue-router under the hood, Nuxt offers you several ways to add custom routes in your project.
Nuxt
middleware/ · Nuxt Directory Structure
Nuxt provides middleware to run code before navigating to a particular route.
MinecraftStorage
MinecraftStorageOP6mo ago
I've found a much better solution that actually is pretty straightforward You can attach the meta property in router.options.js file to a route or a parent route. Like this:
{
path: "create",
component: create,
name: "create",
meta: {
middleware: ["auth"]
}
}
{
path: "create",
component: create,
name: "create",
meta: {
middleware: ["auth"]
}
}
So this meta property can accept all properties available to the definePageMeta function, including middleware. So bad that Nuxt documentation doesn't include that information. I've found it though ChatGPT
Ragura
Ragura6mo ago
You're free to open a PR to add it to the docs! 🙂
Want results from more Discord servers?
Add your server