Search code examples
authenticationfetchnuxt.js

Nuxt and $auth in Fetch()


I have a problem with my $auth...

In a page, i have to verify the $auth.loggedIn value.

<template>
   {{ this.$auth.loggedIn }}
</template>
<script>
   export default{
       async fetch(){
          if(this.$auth.loggedIn){
            console.log('User connected')
          }else{
            console.log('User not connected')
          }
       }
    }
</script>

The first $auth.loggedIn in my template is displaying TRUE (it's ok), but my console.log is displaying "User not connected"...

How it is possible ? It seems i have the same issue with the $router / $route variable...

Thanks a lot! Vincent


Solution

  • fetch is called on server-side when rendering the route, and on client-side when navigating.

    so if it's rendering your route, it initializes at server side and since this.$auth is only available on client-side, it has no access to it.

    try accessing it via app

    async fetch ({ app }) {
          if(app.$auth.loggedIn){
            console.log('User connected')
          }else{
            console.log('User not connected')
          }
    }
    

    regarding param question, you can accessing like below:

    async fetch ({ params }) {
            console.log(params.id)
    }
    

    or

    async fetch ({ route}) {
            console.log(route.params.id)
    }