0

I have created a nuxt application and i have a laravel server for the APIs. On login, the response returns the user object, and auth token. So once login, the $auth.user is set to the user object. The moment i refresh, $auth.user is set to {}, while loggedIn is still true. Please how do i fix this.

This is my login function below

async userLogin() {
  await this.$auth.loginWith('local', { data: this.login })
  .then(async (res) => {
    if(res.data.success){
        const data = res.data.data.user;
        this.$auth.setUser(data)
  })
},

This is my nuxt.config file

  auth: {
    strategies: {
      local: {
        scheme: 'refresh',
        localStorage:{
          prefix: 'auth.'
        },
        token:{
          prefix: 'token.',
          property: 'data.authorization.token',
          type: 'Bearer',
          global: true,
        },
        refreshToken:{
          prefix: 'refresh_token.',
          property: 'data.authorization.token',

        },
        user: {
          property: false,
          autoFetch: false
        },
        endpoints: {
          login: { url: '/login', method: 'post' },
          logout: { url: '/logout', method: 'post' },
          refresh: { url: '/refresh', method: 'post'},
          user: false
        }
      }
    },
    plugins: ['~/plugins/auth.js']
  },

I read somewhere that i should use this.$auth.$storage.setUniversal(user). I tried this but when i login the auth.user object is empty without refreshing.

Please Help!

1 Answers1

0

Looks like you need to set the user endpoint, where you currently have this set to false

If you take a look at the nuxt auth documentation https://auth.nuxtjs.org/schemes/local/#fetch-user

The auth module does not persist information about the user, so there needs to be a way to fetch the user's information on e.g. page reload. That's what the user endpoint is for. By default, this is also called after a successful login.

So this explains why the object is not empty on login, but on refresh it is empty again.

Take a look at this example - note the user endpoint and autoFetch set to true (which is set to true by default)

 auth: {
  strategies: {
    local: {
      token: {
        property: 'token',
        global: true,
        // required: true,
        // type: 'Bearer'
      },
      user: {
        property: 'user',
        autoFetch: true
      },
      endpoints: {
        login: { url: '/api/auth/login', method: 'post' },
        logout: { url: '/api/auth/logout', method: 'post' },
        user: { url: '/api/auth/user', method: 'get' }
      }
    }
  }
}