2

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

kissu
  • 40,416
  • 14
  • 65
  • 133
  • Btw, if you plan to work with `localStorage`, I do recommend this solution since `window` will not always be available (SSR context). – kissu Aug 26 '21 at 23:33

1 Answers1

1

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>
kissu
  • 40,416
  • 14
  • 65
  • 133
  • Thanks for your help. i tried with $router.push(/auth/login). But it says $router is undefined – Sourav Adhikary Aug 26 '21 at 19:27
  • Sir it is perfectly work, when i add this code to individual page and globally (by defining it in nuxt.config.js). But in some pages like login, register it also working there instead of make this middleware to false in those pages. // Login page: export default { role: false; } . How to make this middleware disabled for those specific page? – Sourav Adhikary Aug 27 '21 at 07:10
  • What is `role: false`? Also, do you mind creating a new question for this one? @SouravAdhikary – kissu Aug 27 '21 at 07:49
  • i have created a new question here is the link https://stackoverflow.com/q/68958010/16759400 – Sourav Adhikary Aug 27 '21 at 18:42