title: Firebase Auth and Vue-router
body: <p>I'm trying to authenticate a Vue.js app using firebase. </p>
  
  <p>I have an issue where if trying to access a login-protected URL directly while logged in, the router will load and check for auth state before firebase.js has time to return the auth response. This results in the user being bounced to the login page (while they are already logged in). </p>
  
  <p>How do I delay vue-router navigation until auth state has been retrieved from firebase? I can see that firebase stores the auth data in localStorage, would it be safe to check if that exists as a preliminary authentication check? Ideally the end result would be to show a loading spinner or something while the user is authenticated, then they should be able to access the page they navigated to. </p>
  
  <p>router/index.js </p>
  
  <pre><code>let router = new Router({
    mode: 'history',
    routes: [
      {
        path: '/',
        name: 'Home',
        component: Home
      },
      {
        path: '/login',
        name: 'Login',
        component: Login
      },
      {
        path: '/example',
        name: 'Example',
        component: Example,
        beforeEnter: loginRequired
      }
  })
  
  function loginRequired (to, from, next) {
    if (authService.authenticated()) {
      next()
    } else {
      next('/login')
    }
  }
  </code></pre>
  
  <p>auth.js </p>
  
  <pre><code>import * as firebase from 'firebase'
  
  var config = {
      // firebase config
  }
  
  firebase.initializeApp(config)
  
  var authService = {
  
    firebase: firebase,
    user: null,
  
    authenticated () {
      if (this.user == null) {
        return false
      } else {
        return !this.user.isAnonymous
      }
    },
  
    setUser (user) {
      this.user = user
    },
  
    login (email, password) {
      return this.firebase.auth().signInWithEmailAndPassword(email, password)
        .then(user =&gt; {
          this.setUser(user)
        })
    },
  
    logout () {
      this.firebase.auth().signOut().then(() =&gt; {
        console.log('logout done')
      })
    }
  }
  
  firebase.auth().onAuthStateChanged(user =&gt; {
    authService.setUser(user)
  })
  
  export default authService
  </code></pre>
  
  <p>app.vue </p>
  
  <pre><code>&lt;template&gt;
    &lt;div id="app"&gt;
      &lt;p v-if="auth.user !== null"&gt;Logged in with {{ auth.user.email }}&lt;/p&gt;
      &lt;p v-else&gt;not logged in&lt;/p&gt;
      &lt;router-view v-if="auth.user !== null"&gt;&lt;/router-view&gt;
    &lt;/div&gt;
  &lt;/template&gt;
  
  &lt;script&gt;
  import authService from './auth'
  
  export default {
    name: 'app',
    data () {
      return {
        auth: authService
      }
    }
  }
  &lt;/script&gt;
  </code></pre>