Auth0 Home Blog Docs

Conditional redirect based on authentication using state to save original url request



I am having some trouble configuring a VueJs + Auth0 application to redirect the user based on the original requested url, and the authentication status. I want to implement the following logic:

  • original url is / and user is not authenticated, then redirect to /#/landing.
  • original url is /app/* and the user is authenticated, then redirect to original url.
  • original url is /app/* and the user is not authenticated, then, show Auth0Lock modal to authenticated and redirect to original URL.

This is what I am doing:

In the main component App.vue, I initialize Auth0Lock in the mounted() hook with the current path obtained as this.$route.path and use this to set auth.state. I also configure the on('authenticated') callback to redirect the user to the ‘Root’ page after authentication. This seems to work.

Here is the App.vue mounted hook:

mounted () {
  var options = {
    auth: {
      state: this.$route.path,
      responseType: 'token',
      params: {
        connectionScopes: {
          connectionName:  'openid', 'user_metadata', 'app_metadata', 'picture' ]

  var lock = new Auth0Lock(process.env.AUTH0_CLIENT_ID, process.env.AUTH0_DOMAIN, options)

  lock.on('authenticated', (authResult) => {
    localStorage.setItem('access_token', authResult.accessToken)
    localStorage.setItem('id_token', authResult.idToken)
    this.$store.commit('authenticate', !!localStorage.getItem('id_token'))
    this.$store.commit('setAuth0state', authResult.state)
    this.$router.push({ name: 'Root' })

The ‘Root’ page is mapped to / and loads a simple component in which the redirection logic is executed.

Here is the Root.vue mounted hook:

mounted () {
  if (this.$store.state.user.authenticated) {
    var path = this.$store.state.user.auth0state
    if (!path.startsWith('/app')) {
      this.$router.push({ name: 'InitiativesHome' })
    } else {
  } else {
    this.$router.push({ name: 'Landing' })

The problem is that it works every now and then. Some times, the path is the originally requested path (meaning that saving it in auth.state worked), but other times, the path is filled with all the access_token data like


I’ve been struggling with finding a clean redirection logic that can redirect the user to the original requested url or to the landing page