title: How to implement asynchronous middleware in Nuxt.js
body: <p>I have a Nuxt middleware file that fetches the session from an external api. This session is used to set things such as locale, so it's important that it is fetched before any page loads. Currently it looks like this:</p>
  
  <p><strong>middleware/session.js</strong></p>
  
  <pre><code>import axios from 'axios'
  
  export default function ({ store }) {
    axios.get('http://example.com/getsession')
      .then(response =&gt; {
        store.commit('setSession', response)
      })
      .catch(() =&gt; {
        store.commit('clearSession')
      })
  }
  </code></pre>
  
  <p><strong>store/index.js</strong></p>
  
  <pre><code>export const state = () =&gt; ({
    session: {}
  })
  
  export const mutations = {
    setSession (state, session) {
      state.session = session || {}
    },
    clearSession (state) {
      state.session = {}
    }
  }
  
  export const getters = {
    session (state) {
      return state.session || {}
    }
  }
  </code></pre>
  
  <p>The session is fetched using Axios and stored in a Vuex store. However, since it is asynchronous, this data isn't available instantly, and plugins or other middleware that try to get the session from the store simply get an empty object (which is the default).</p>
  
  <p>Examples where this breaks things:</p>
  
  <ul>
  <li>Another middleware used for certain routes checks if the user is logged in based on the <code>session.user</code>. The session is still empty and therefore <code>session.user</code> is <code>undefined</code> at this point.</li>
  <li>I'm using the vue-i18n plugin to translate pages. It gets its initial locale from the session in the store. But since this session is empty at the moment it is retrieved, i18n always uses the fallback locale.</li>
  </ul>
  
  <p>Is there a way to await the response of the api call before proceeding? Or is there maybe a different/better way to perform this api call?</p>