javascriptvue.jsnuxt.jsnuxt-auth

How logout user when one of APIs responds Unauthorized 401 (Nuxt-Auth)


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'},
                },
            },
        }
    },


Solution

  • 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
        }
      })
    }