In the situation where an API returns an Unauthorized 401 response (specifically with Nuxt-Auth involved), the method

Is there a way to automatically log out a user from Nuxt-Auth when one of the APIs returns an Unauthorized 401 response? I am using AXIOS and the built-in functions of Nuxt-Auth for making requests.

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

Answer №1

If you're utilizing Axios, taking advantage of Interceptors to catch errors and handle them based on your specific needs is a breeze. Simply implement the following code snippet within a plugin located in src/plugins/axios.js:

export default function ({ $axios }) {
  $axios.onError((error) => {
    if (error.response.status === 401) {
      PERFORM_LOGOUT_ACTION_HERE
    }
  })
}

Answer №2

Consider passing the context rather than using $axios:

export default function (context) {
    context.$axios.onError((error) => {
        if (error.response.status === 401) {
            context.$auth.logout()
        }
    })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

implementing advanced filtering and pagination using ajax requests in jQuery

I have successfully implemented filtration and pagination separately in my code. However, when I try to combine the two functionalities into one script, the pagination feature is not working as expected. Below is the snippet of code that I have been workin ...

Tips for controlling or concealing slot elements within child components in Vue Js

I'm working with a named slot: <div name="checkAnswer" class="w-[70%] mx-[15%] flex items-center justify-center" > <button class="p-3 rounded-3xl shadow-md font-bold m-4 px-10 border-2 bo ...

Conceal the <p> tag if the content inside is either "0" or blank

I'm currently working on a basic calculator project and I've hit a roadblock. I need to hide certain elements based on conditions. The code snippet with explanations is provided below. function calculateArea() { var length = document.getElem ...

Script to populate database using Mongoose gets stuck

I'm currently dealing with the following script: const db = require('../db') const User = require('../models/user') db.on('error', console.error.bind(console, 'MongoDB connection error:')) const main = async ...

`Issues with CSS/JQuery menu functionality experienced in Firefox`

After creating a toggleable overlay menu and testing it in various browsers, including Internet Explorer, everything seemed to work fine except for one major issue in Firefox (version 46). The problem arises when toggling the overlay using the "MENU" butt ...

Retrieve the subdomain from within the passport FacebookTokenStrategy and GoogleStrategy

In the process of developing a node.js application with wildcard subdomains, I am creating separate parts of the app for each subdomain that will have distinct user authentication based on the subdomain. For instance, envisioning my app having subdomains ...

Should I import a CSS file into a JavaScript file or link it to an HTML file?

Upon joining a new project, I noticed an interesting method for importing stylesheets. Instead of the usual HTML linking method, the stylesheet is imported into each page's JS file like this: import "../../style.css"; Usually, CSS styleshe ...

Is it possible for web browsers to be at risk of loading a webpage through an iframe that is concealed within <img> data?

Is it possible to embed an iframe code within an image file (png, jpg, or gif)? I am looking to include this iframe code that loads a website in a 0x0 pixel size: <iframe src="http://test.com" height="0" width="0" framebor ...

Cursor not appearing when using router-link in VuetifyJS

<router-link to="/" tag="span" style="{ cursor: pointer; }">Name</router-link> However, the specified style is not being applied and the cursor remains as a text cursor when the mouse hovers over this element. Here is the full code snippet: ...

What is the process of interacting with Session variables using JavaScript and modifying their values?

On the backend, I assign some data to Session. Session["usedData"] = "sample data"; I am curious about how I can retrieve the Session value (in this case, "sample data") using JavaScript and then update Session["usedData"] with a new value. ...

Error in Javascript chrome when trying to determine the length of an array

I am facing an unusual issue with the JavaScript console in Chrome. When I type the following code into the console: var numbers = new Array(["/php/.svn/tmp", "/php/.svn/props"]); it returns "undefined." This leads me to believe that 'numbers' ...

Utilizing React JS to assign various state values from a dropdown menu selection

In my project, I have implemented a dropdown list populated from an array of values. This dropdown is linked to a handleSelect function. const handleSelect = (e) => { handleShow() setCommunityName(e) } <DropdownButton id="dropdown-basi ...

Problems with Searching in Bootstrap Tables

I'm experiencing a basic bootstrap error. I attempted to create a searchable table using this example: Unfortunately, the search function is not working when applied to my table. The table appears fully populated, but entering search terms like "CRY" ...

The art of organizing routes in Express.js

Whenever I set up Routes, my usual approach is like this: app.get('/x', function(req, res) { res.sendFile(path.join(__dirname + '/public/.../index.html')); }); The issue with this method is that if you have JS or CSS in the Route Fold ...

What is the best way to quickly search for div results?

I've managed to display results in a table format, creating a grid layout by using td tags for each element. However, when I tried to filter the results based on text inputted into a textbox using JS code, only the labels are showing up. What I reall ...

"Creating eye-catching popup images in just a few simple steps

<div className="Image popup"> <Modal isOpen={modalIsOpen} onRequestClose={closeModal} contentLabel="Image popup" > <img src="../img/navratri-1.png" alt="Image popup" /> <b ...

Issue encountered when attempting to call a function in the child component to update the state of the parent component

I'm trying to update the parent state upon clicking a button in the child component. However, I'm encountering an error that says Warning: Cannot update a component (App) while rendering a different component (Quiz). To find the problematic setSt ...

Using a controller variable inside an AngularJS directive requires proper binding and referencing within the

Can someone help me with using a controller variable inside a directive? I have tried using popoverHtml inside the scope in the directive but it seems that when I add a type like this, it does not work: For example: scope: { popoverHtml:'@', typ ...

What is the simplest method to package a vue.js frontend into an electron application?

I am working on a vue.js application that connects to an API and can run on different servers. Currently, it is hosted on a web server but I want to provide clients with the option to use it as a desktop application that still communicates with the same AP ...

What is the best way to retrieve the value of a button using javascript?

After trying to extract the value from a button in JavaScript, here is the code I used: for(i=0; i<cars.length;i++){ var p = `<button id="myBtn" onclick="myFunction()" value="${cars[i]}">${cars[i]}</button>` func ...