0
votes

i have declare a middleware that check role of every routes in nuxt.config.js. but want to disable in some pages.

// in nuxt.config.js =>        
        router: {
            middleware: ['role']
          },
        
        
        
 // in middleware/role.js =>     
        export default function ({app}) {
          if (!window.localStorage.getItem('auth.token')) {    
            //app.router.push('/auth/login');   
            console.log('middleware');
          }
        }
        
        
 // in login.vue =>     
            export default {
                role: false,
              }
    
    
 // in root page =>
        export default { 
          role: false,               
          middleware({app}){
            if (!window.localStorage.getItem('auth.token')) {
              app.router.push('/auth/login');
            }
          },    
      }

when token is empty and redirect user, the page is loading again and again so i comment this redirect and console log a message, to check what happen. this role middleware is loading on that page where the role middleware is set to false. check the image below.

image of browser console

here you can see middleware printed twice, one for root('/') and another one for login page (here i disabled role middleware). how to disable this middleware to this login page.

1
you can check route.path in middleware and return if this variable equal your path. - m kh

1 Answers

0
votes

You can use this

middleware({ route }) {
  if (!['do-not-run-here', 'public-page', 'index'].includes(route.name)) return

  // all your cool code here
  console.log('passed')
},

You can have some quick return in case this is a page you don't want to have a middleware. In my example, we do check the name of the route, and if it's do-no-run-here, public-page or index the middleware is simply not executed there.
Of course, setting a name prop is good if you want to be sure of the name of the page.

On all the other ones, the middleware will run perfectly fine. There is no middleware: false if it's what you were looking for.


An alternative solution would be to use a specific layout for some pages, with the middleware on it. And not use this one for the pages you don't want to have the middleware on.