Search code examples
javascriptvue.jsnuxt.jsvuex

Get localStorage data in nuxt layout function


I have such a problem: I need to get localStorage data before nuxt layout is loaded in pages/index.vue

/pages/index.vue

<script>
export default {
  layout (context) {
    if (localStorage.getItem('AUTH_TOKEN')){
      this.$store.dispatch('changeAuthStatus', {
        authStatus: true,
        accessToken: localStorage.getItem('AUTH_TOKEN'),
        profileData: JSON.parse(localStorage.getItem('PROFILE_DATA'))
      }).then(() => {
        this.$store.dispatch('changeLoadedStatus', {
          isLoaded: true
        })
      })
    }
    else {
      this.$router.push('/auth')
    }
  }
</script>

The error when the page is loaded: localStorage is not defined

Maybe I can get localStorage data using context? Or maybe you can suggest to me any package so I can use it in the layout function?


Solution

  • I found the solution:

    I just installed nuxt-universal-storage module, that Amirhossein Shahbazi suggested. So I have just done this:

    /pages/index.vue:

    <script>
    export default {
    middleware: ['auth'],
      layout (context) {
        let currentRole = context.app.$storage.getUniversal('PROFILE_DATA')
        console.log(currentRole)
        let currentLayout = 'default'
        let defaultRoles = ['customer_support_manager', 'checker', 'storekeeper']
        let tabletRoles = ['deputy_cutting_shop']
        if (defaultRoles.includes(currentRole.role)) {
          currentLayout = 'default'
        }
        else if (tabletRoles.includes(currentRole.role)) {
          currentLayout = 'tablet'
        }
        return currentLayout
    }
    </script>
    

    /middleware/auth.js:

    export default function ({ redirect, app, store }) {
        // some token checkers for existing, for 401 error and for their validity
    }