0

How logout user when one of APIs responds Unauthorized 401 with Nuxt-Auth? I use AXIOS & built-in functions of Nuxt-Auth for requests

My nuxt-config settings for nuxt-auth:

    auth: {
        redirect: {
            login: '/login',
            logout: '/',
            callback: '/login',
            home: '/panel/dashboard'
        },
        strategies: {
            local: {
                token: {
                    property: 'token',
                    global: true,
                    type: 'Bearer',
                    required: true,
                },
                user: {
                    property: 'user',
                    autoFetch: true
                },
                endpoints: {
                    login: {url: '/api/auth/login_verify', method: 'post'},
                    logout: {url: '/api/auth/logout', method: 'get'},
                    user: {url: '/api/auth/validate', method: 'get'},
                },
            },
        }
    },
Mehdi Rafiee
  • 89
  • 2
  • 12

2 Answers2

5

Since you're using Axios, it'll be easy to use Interceptors and catch the error according to your requirement and then call the logout action

Something like below with a plugin created in src/plugins/axios.js will work

export default function ({ $axios }) {
  $axios.onError((error) => {
    if (error.response.status === 401) {
      CALL_LOGOUT_ACTION_HERE
    }
  })
}
UdithIshara
  • 405
  • 3
  • 7
  • That will destroy default nuxt header on error, and app will be lagged in some request –  Jul 04 '22 at 18:55
  • 1
    $auth is not present here how are you calling the logout action? – aks Aug 18 '22 at 09:42
1

pass context instead of $axios:

export default function (context) {
    context.$axios.onError((error) => {
        if (error.response.status === 401) {
            context.$auth.logout()
        }
    })
}
Derek Pollard
  • 6,953
  • 6
  • 39
  • 59