0

I have a very simple 'named' Nuxt middleware set up (taken from the docs) which checks in the store to see whether a user is authenticated before they can navigate to certain routes. If the user is not authenticated, they are directed to a straightforward form in which they have to provide an email address to gain access (at http://example.com/access). All of that works fine, after they fulfil the middleware's store.state.authenticated check they can navigate around no problem.

export default function ({ store, redirect }) {
  if (!store.state.authenticated) {
    return redirect('/access')
  }
}

My question is, once the user has entered their email address, I have no way of knowing what route they were initially trying to access. I've looked at other questions here about passing data between routes but because of the way the middleware works these solutions don't seem to be feasible.

I really would rather not set the slug in the vuex state as this will lead to a whole other set of complications – I also don't mind setting the intended slug as a query or a param on the /access url. I have read through the docs for the Nuxt redirect function and realise you can pass a route.query as an argument. So it seems that you could potentially do something like this:

return redirect('/access', intendedSlug)

...or, if using params(?):

return redirect(`/access/${intendedSlug}`)

But I don't know how to pass that intendedSlug value to the middleware in the first place as it's not exposed on the context passed to the function or anywhere else. It seems like this would be a common problem, but I can't find any simple solutions – any help would be really appreciated!

Jack Clarke
  • 499
  • 5
  • 20

1 Answers1

0

To help @Bodger I'm posting how I resolved this, it may not be perfect and it's working on a slightly older version of Nuxt (I know !) but this is how I resolved the issue.

.../middleware/authenticated.js

export default function (context) {
  const path =
    context.route.path.length && context.route.path[0] === '/'
      ? context.route.path.slice(1)
      : context.route.path
  const pathArray = path.split('/')
  if (process.server && !context.store.state.authenticated) {
    return context.redirect('/access', pathArray)
  } else if (!context.store.state.authenticated) {
    return context.redirect('/access', pathArray)
  }
}

The pathArray is then accessible in my /access page.

.../pages/access.js

data() {
    return {
      attemptedRoutePathArray: Object.values(this.$route.query)
      ...
    }
  },
...
computed: {
    attemptedRouteURL() {
      return new URL(
        this.attemptedRoutePathArray.join('/'),
        process.env.baseUrl
      )
    },
    ...
}
Jack Clarke
  • 499
  • 5
  • 20