0

Using Nuxt-Auth, is there an official way to check if a route is protected (ie requires login)?

In some sample middleware, doing a console log of "route" shows a large JSON payload with some mentions of middleware: 'auth'. However how reliable is this method? What if the JSON structure changes in the future?

export default function({ $auth, route }) {

    // This returns 'auth' for protected routes; undefined for unprotected routes.
    // But how reliable is this method? The JSON structure could change in the future.
    console.log(route.matched[0].components.default.options.middleware)

}
Kalnode
  • 9,386
  • 3
  • 34
  • 62

1 Answers1

0

I've found out a solution for me. Maybe it'll help you. There is a function in auth-next/runtime.js file. I've copied it to the my file

function routeOption(route, key, value) {
  return route.matched.some((m) => {
    if (process.client) {
      return Object.values(m.components).some((component) => component.options && component.options[key] === value)
    } else {
      return Object.values(m.components).some((component) => Object.values(component._Ctor).some((ctor) => ctor.options && ctor.options[key] === value))
    }
  })
}

Then you can use it this way:

console.log('Auth not required: ', routeOption(ctx.route, 'auth', false))
Vrnkp
  • 1