Nuxt.js: Allow middleware to be applied to route groups

Created on 16 Feb 2019  路  1Comment  路  Source: nuxt/nuxt.js

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

  1. nuxt.config.js

    1. Global middleware

    2. Group middleware

  2. Matched layouts
  3. 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).

This feature request is available on Nuxt community (#c8673)
feature-request

>All comments

@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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

msudgh picture msudgh  路  3Comments

bimohxh picture bimohxh  路  3Comments

surmon-china picture surmon-china  路  3Comments

pehbehbeh picture pehbehbeh  路  3Comments

o-alexandrov picture o-alexandrov  路  3Comments