title: Using vue.js and Auth0 how can i skip the login page if the user's already authenticated?
body: <p><strong>DESCRIPTION</strong></p>
  
  <p>I have a pretty standard <code>SPA</code> built with <code>vue.js</code> where I'm using <code>Auth0</code> to handle the authentication  part by following the <a href="https://auth0.com/docs/quickstart/spa/vuejs#display-the-user-s-profile" rel="noreferrer">official</a> example. The app flow is as follows:</p>
  
  <p><code>Register in the Initial.vue via Auth0 lock</code> -> <code>Callback is called</code> -> <code>User's redirected to /home</code></p>
  
  <p>Everything in the above flow works fine but here's the problem:</p>
  
  <p><strong>PROBLEM</strong></p>
  
  <p>Once the user's registered and in the <code>/home</code> I want him to be able to access all the other routes (e.g. <code>/doctors</code>) if authenticated and if not he should be prompter to login again. According to the above link this is handled in the <code>router.beforeEach</code> function. </p>
  
  <p><em>My problem</em> appears when accessing the <code>/</code> login page (<code>Initialvue</code>). When the user's already registered and trying to access that route I want him to get redirected to the <code>/home</code> and skip the <code>login</code> page. I've tried implementing this with a <code>beforeEnter</code> route but <code>auth.isAuthenticated</code> fails due to the <code>tokenExpiry</code> being null (even-though user's authenticated!</p>
  
  <p><strong>CODE</strong></p>
  
  <p>My <code>AuthService.js</code>:</p>
  
  <pre><code>import auth0 from 'auth0-js';
  import EventEmitter from 'events';
  import authConfig from '../config/auth_config.json';
  
  const webAuth = new auth0.WebAuth({
    domain: authConfig.domain,
    redirectUri: `${window.location.origin}/callback`,
    clientID: authConfig.clientId,
    responseType: 'id_token',
    scope: 'openid profile email'
  });
  
  const localStorageKey = 'loggedIn';
  const loginEvent = 'loginEvent';
  
  class AuthService extends EventEmitter {
    idToken = null;
    profile = null;
    tokenExpiry = null;
  
    // Starts the user login flow
    login(customState) {
      webAuth.authorize({
        appState: customState
      });
    }
  
    // Handles the callback request from Auth0
    handleAuthentication() {
      return new Promise((resolve, reject) =&gt; {
        webAuth.parseHash((err, authResult) =&gt; {
          if (err) {
            reject(err);
          } else {
            this.localLogin(authResult);
            resolve(authResult.idToken);
          }
        });
      });
    }
  
    localLogin(authResult) {
      // console.log(authResult); TODO-me: Handle this
      this.idToken = authResult.idToken;
      this.profile = authResult.idTokenPayload;
  
      // Convert the JWT expiry time from seconds to milliseconds
      this.tokenExpiry = new Date(this.profile.exp * 1000);
  
      localStorage.setItem(localStorageKey, 'true');
  
      this.emit(loginEvent, {
        loggedIn: true,
        profile: authResult.idTokenPayload,
        state: authResult.appState || {}
      });
    }
  
    renewTokens() {
      return new Promise((resolve, reject) =&gt; {
        if (localStorage.getItem(localStorageKey) !== "true") {
          return reject("Not logged in");
        }``;
  
        webAuth.checkSession({}, (err, authResult) =&gt; {
          if (err) {
            reject(err);
          } else {
            this.localLogin(authResult);
            resolve(authResult);
          }
        });
      });
    }
  
    logOut() {
      localStorage.removeItem(localStorageKey);
  
      this.idToken = null;
      this.tokenExpiry = null;
      this.profile = null;
  
      webAuth.logout({
        returnTo: window.location.origin
      });
  
      this.emit(loginEvent, { loggedIn: false });
    }
  
    isAuthenticated() {
       console.log('In tokenExp is:');
       console.log(this.tokenExpiry); //THIS returns null when /home -&gt; /
      return (
        Date.now() &lt; this.tokenExpiry &amp;&amp;
        localStorage.getItem(localStorageKey) === 'true'
      );
    }
  }
  
  export default new AuthService();
  </code></pre>
  
  <p>My <code>Initial.vue</code>:</p>
  
  <pre><code>&lt;template&gt;
      &lt;v-container
          app
          fluid
      &gt;
          &lt;v-parallax
              src="https://cdn.vuetifyjs.com/images/backgrounds/vbanner.jpg"
              height="1000"
          &gt;
              &lt;v-layout
                  row
                  wrap
              &gt;
                  &lt;!-- LOGIN--&gt;
  
                      &lt;v-toolbar
                          flat
                          light
                          dense
                          color="transparent"
                      &gt;
                          &lt;v-spacer&gt;&lt;/v-spacer&gt;
                          &lt;v-toolbar-items&gt;
                              &lt;v-btn
                                  medium
                                  color="lime lighten-2"
                                  @click="login"
                                  class="font-weight-bold title text-uppercase"
                              &gt;
                                  Login
                              &lt;/v-btn&gt;
                          &lt;/v-toolbar-items&gt;
                      &lt;/v-toolbar&gt;
              &lt;v-layout
                  align-center
                  column
              &gt;
                  &lt;h1 class="display-2 font-weight-thin mb-3 text-uppercase lime--text lighten-2" &gt;Pulse&lt;/h1&gt;
                  &lt;h4 class="subheading"&gt;A digital intelligent insurance built for you!&lt;/h4&gt;
              &lt;/v-layout&gt;
  
              &lt;/v-layout&gt;
          &lt;/v-parallax&gt;
      &lt;/v-container&gt;
  &lt;/template&gt;
  
  &lt;script&gt;
      import VContainer from "vuetify/lib/components/VGrid/VContainer";
      import VFlex from "vuetify/lib/components/VGrid/VFlex";
      import VLayout from "vuetify/lib/components/VGrid/VLayout";
      import VBtn from "vuetify/lib/components/VBtn/VBtn";
      import VToolbar from "vuetify/lib/components/VToolbar/VToolbar";
      import VParallax from "vuetify/lib/components/VParallax/VParallax";
  
      export default {
          name: "Initial",
          components: {
              VContainer,
              VLayout,
              VFlex,
              VBtn,
              VToolbar,
              VParallax
          },
          data() {
              return {
              isAuthenticated: false
              };
          },
          async created() {
              try {
                  await this.$auth.renewTokens();
              } catch (e) {
              // console.log(e);
              }
          },
          methods: {
              login() {
                  this.$auth.login();
          },
              // logout() {
              //     this.$auth.logOut();
              // },
              handleLoginEvent(data) {
                  this.isAuthenticated = data.loggedIn;
                  this.profile = data.profile;
              }
          }
  
  
      }
  &lt;/script&gt;
  
  &lt;style scoped&gt;
  
  &lt;/style&gt;
  </code></pre>
  
  <p>My <code>Callback.vue</code>:</p>
  
  <pre><code>&lt;template&gt;
    &lt;div&gt;
      &lt;p&gt;Loading...&lt;/p&gt;
    &lt;/div&gt;
  &lt;/template&gt;
  
  &lt;script&gt;
      export default {
        methods: {
          handleLoginEvent(data) {
              console.log('State.target is:');
              console.log(data.state.target);
            //If user has just signed up redirect to complete-signup form
            if ((data.profile['&lt;AUTH_DOMAIN&gt;'].justSignedUp) &amp;&amp; (data.state.target===undefined)){
                // this.$router.push(data.state.target || "/complete-signup");
                this.$router.push('/complete-signup');
                }else {
                    // this.$router.push('/home');
                    this.$router.push(data.state.target);
                }
          }
        },
        created() {
          this.$auth.handleAuthentication();
        }
      }
  
  &lt;/script&gt;
  
  &lt;style scoped&gt;
  
  &lt;/style&gt;
  </code></pre>
  
  <p>My <code>router.js</code>:</p>
  
  <pre><code>import Vue from 'vue';
  import Router from 'vue-router';
  import auth from '../auth/AuthService';
  
  import Callback from '../components/Callback';
  
  Vue.use(Router)
  
  // export default new Router({
  const router = new Router({
      mode: 'history',
      base: process.env.BASE_URL,
      routes: [
          // {
          //     path: '/',
          //     name: 'login',
          //     component: () =&gt; import('@/views/Login')
          // },
          {
              path: '/',
              name: 'initial',
              component: () =&gt; import('@/views/Initial'),
              // meta: {isAuth: true},
              beforeEnter: ((to, from, next) =&gt; {
                  // if (to.matched.some(record =&gt; record.meta.isAuth)) {
                       console.log(auth.isAuthenticated()); //THIS is false for the above scenario
                      if (auth.isAuthenticated()) {
                          next({
                              path: '/home',
                              query: {redirect: to.fullPath}
                          })
                      } else {
                          next()
                      }
                  // }
              })
  
          },
          {
              path: '/callback',
              name: 'callback',
              component: Callback
          },
          {
              path: '/home',
              name: 'home',
              component: () =&gt; import('@/views/Home')
          },
          {
              path: '/doctors',
              name: 'doctors',
              component: () =&gt; import('@/views/Doctors')
          },
          {
              path: '/complete-signup',
              name: 'complete-signup',
              component: () =&gt; import('@/views/CompleteSignup')
          },
  
      ]
  });
  
  // Add a `beforeEach` handler to each route
  router.beforeEach((to, from, next) =&gt; {
    if (to.path === "/" || to.path === "/callback" || auth.isAuthenticated()) {
      return next();
    }
  
    // Specify the current path as the customState parameter, meaning it
    // will be returned to the application after auth
      console.log('OUT beforeach if');
    auth.login({ target: to.path });
  });
  </code></pre>
  
  <p>The 'CompleteSignup<code>is my signup form after registering where the user's is filling out a form and then posting it via</code>axios<code>and then redirected to</code>/home`: </p>
  
  <pre><code>//Form data before
  methods: {
  this.$store.dispatch(REGISTER,registerFormData)
            .then(() =&gt; this.$router.push('/home'));
  }
  </code></pre>
  
  <p>I'm also using <code>vuetify</code> and my main <code>App.vue</code> component is:</p>
  
  <pre><code>&lt;template&gt;
  
      &lt;v-app
          style= "background: #E0EAFC;  /* fallback for old browsers */
          background: -webkit-linear-gradient(to left, #CFDEF3, #E0EAFC);  /* Chrome 10-25, Safari 5.1-6 */
          background: linear-gradient(to left, #CFDEF3, #E0EAFC); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
          "
      &gt;  
        &lt;v-content&gt;
          &lt;router-view&gt;&lt;/router-view&gt;
        &lt;/v-content&gt;
      &lt;/v-app&gt;
  &lt;/template&gt; 
  
  
  &lt;script&gt;   
    export default {
        name: 'App',
        components: {
  
        }
  
    };
  
  
  &lt;/script&gt;
  
  &lt;style&gt;
  &lt;/style&gt;
  </code></pre>