1

I'm using NuxtJs v2.13 with its auth module and Laravel with passport for my backend. for login i use the documented method:

async signIn(formData){
  await this.$auth.loginWith('local',{
    data: formData
  })
  if(this.$auth.user.depth > 1){
    this.goTo('/cms/product')
  }else{
    this.goTo('/')
  }
}

when the email or password is wrong it send me too nuxt error page! i should remain on login page. what should i do!!?

BTW, i gonna use vee-validate on my form too. and this is my auth config on nuxt.config.js:

auth: {
      strategies: {
        local: {
          endpoints: {
            login: { url: 'auth/login', method: 'post', propertyName: '' },
            logout: { url: 'auth/logout', method: 'post' },
            user: { url: 'auth/info', method: 'get', propertyName: 'data' }
          }
        }
      },
      redirect: {
        login: '/login',
        logout: '/',
        callback: '/login',
        home: '/'
      },
      cookie: {
        prefix: 'auth.',
        options: {
          path: '/',
          maxAge: process.env.AUTH_COOKIE_MAX_AGE
        }
      }
  },
Mojtaba Barari
  • 1,127
  • 1
  • 15
  • 49

1 Answers1

1

Nuxt is redirecting because the error isn't being handled. You can simply wrap this code in an error handler. It's also good to put this code near the login component or page so you can use the status code of the error to display some meaningful response to the user, e.g. that the credentials were invalid.

try {
  await this.$auth.loginWith('local', {
    data: formData,
  })
  if (this.$auth.user.depth > 1) {
    this.goTo('/cms/product')
  } else {
    this.goTo('/')
  }
} catch (error) {
  if (error.response) {
    // Get the error status, inform the user of the error.
  }

  // Unexpected error, tell the user to try again later.
}

Since the @nuxtjs/auth package requires the @nuxtjs/axios package you can also read about intercepting errors on a global level with Axios Interceptors. I personally use try/catch blocks at the method level and use interceptors for catching 401 Unauthenticated errors and deleting the user information from Vuex.

Duckie
  • 31
  • 4