vue.jsnuxt.jsvue-routermiddlewarenuxt-auth

Redirect user based on their role via nuxt middleware


i want to redirect user based on their role & other attributes via nuxt middleware.

** Redirection happen but got stuck into navigation guard, and page automatically reload again and again (reload ~500 times in second).

#here is my code

nuxt.config.js

router: {
  middleware: ['role']
},

middleware/role.js

export default function ({ redirect }) {
  if (!window.localStorage.getItem('auth.token')) {
    return redirect('/auth/login')
  }
}

the screenshot of browser console


Solution

  • A redirect is a brand new page load like if you reach a page for the first time or if you F5 on it. Since you're doing some condition here, it will always make a redirect, the Vue app will load, call the middleware again in an infinite loop.

    Either make a router.push or check if the initial page is not the one you were already on before the redirect (not the best idea IMO).

    Updated answer

    In the middleware context, if you want to access the router, you need to use this

    <script>
    export default {
      middleware({ app }) {
        if (somethingTrue) { // your condition here
          app.router.push('/')
        }
      },
    }
    </script>