nuxt
nuxt copied to clipboard
Allow middleware to be applied to route groups
What problem does this feature solve?
In real-world use cases you often have to apply middleware to a group of routes. Currently however there's only native capabilities to apply middleware to single routes or apply them globally. When you want to apply the middleware to a group of routes, you have to either check for the route within the middleware (which kills reusability) and apply it globally, or add it to each route within the group individually, making it easy to forget when creating new routes.
An example is a middleware for authenticated routes. Most times you don't just have a single page that requires authentication, you have a group of routes. In the following file tree, we might want to add a middleware that checks for an authenticated user and for admin permissions to all routes within admin/
.
pages/
--| admin/
-----| users/
--------| _slug.vue
--------| index.vue
-----| index.vue
--| index.vue
--| login.vue
To do so, we could add the middleware to the current three pages and remember to also add it to all new pages. We could also add the middleware globally, but not execute the check when the route is not within admin/
, but as stated above, this removes the reusability of the middleware.
What does the proposed changes look like?
Without knowing too much about the internal of nuxt.js, I propose adding a separate router configuration option. An example API could be
module.exports = {
// ...
router: {
middleware: ['demo'],
groupMiddleware: {
'admin/': ['auth', 'admin']
}
}
}
The new execution order for middleware would then be
-
nuxt.config.js
- Global middleware
- Group middleware
- Matched layouts
- Matched pages
All routes whose full path then start with admin/
would have the auth
and admin
middleware applied to them (in addition to demo
from global middlewares).
@padarom You can achieve this by creating a vue file called
admin.vue
at the same level as your admin
folder. the vue file should contain a nuxt-child
component at that point you can add the middleware in the admin.vue
and it will work for all the children too.
We are approaching the Nuxt 2 EOL date (June 30, 2024) - see this article for more information. I'm closing this issue as it's marked as a Nuxt 2 related enhancement and it's not a critical issue.
That doesn't mean it might not be relevant for Nuxt 3. If it is, please feel free to open a new issue (or just comment, and I can reopen it). 🙏
Thank you for your understanding and for your contribution to Nuxt! 🎉