Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

46
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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
}
about 4 years ago · Juan Pablo Isaza Relatório

0

If I'm not mistaken, Nuxt is the SSR solution for Vue (same as Next for React), right?

If so, you don't have access to the localStorage. Server Side is not running in your browser!

about 4 years ago · Juan Pablo Isaza Relatório

0

This kind of code works fine

<script>
export default {
  layout({ store }) {
    if (process.client) {
      console.log('localStorage?', localStorage.getItem('myCat'))
      console.log('store?', store)
    }
  },
}
</script>

Because localStorage is not available on the server.

Try to use localStorage.setItem('myCat', 'Tom'), move to your page and see how it displays the localStorage and the store (don't forget to use the context since this is not available here).

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda