Skip to content

Instantly share code, notes, and snippets.

@yajra
Last active September 20, 2023 06:24
Show Gist options
  • Save yajra/5f5551649b20c8f668aec48549ef5c1f to your computer and use it in GitHub Desktop.
Save yajra/5f5551649b20c8f668aec48549ef5c1f to your computer and use it in GitHub Desktop.
Axios 401 response interceptor.
// Add a 401 response interceptor
window.axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
if (401 === error.response.status) {
swal({
title: "Session Expired",
text: "Your session has expired. Would you like to be redirected to the login page?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
closeOnConfirm: false
}, function(){
window.location = '/login';
return Promise.reject(error)
});
} else {
return Promise.reject(error);
}
});
@sameeramrutia
Copy link

Where should I place this code?

@sagar-gavhane
Copy link

Use above snippets inside index.js file (entry point) or at axios configuration file. Ref: https://github.com/axios/axios#interceptors

@HogansJoe
Copy link

Thanks great work!

@m4ss1m0g
Copy link

In case of redirect to login page you do not fulfill the promise.
You must return Promise.reject(error); after window.location

@behnamazimi
Copy link

What about the server side rendering?
Is there any solution for that?

@NaturalDevCR
Copy link

Thanks for this! worked smoothly

@hrb-suzuki
Copy link

thanks:)
It was very helpful.

@juancarloselorriaga
Copy link

Thank you very much :)

@estani
Copy link

estani commented Dec 10, 2019

I can't seem to get it to work, I get a "Network Error" without any response... I see I get a 401 in the browser network panel. Any Idea? Did this change?
Answer: It was a problem with CORS and how it was setup, so axios never got the information back from the browser. This should work as is

@Avto9711
Copy link

I can't seem to get it to work, I get a "Network Error" without any response... I see I get a 401 in the browser network panel. Any Idea? Did this change?
Answer: It was a problem with CORS and how it was setup, so axios never got the information back from the browser. This should work as is

Can you explain what you did or how you solved?

@estani
Copy link

estani commented Jan 14, 2020

Nothing on the client side, this is a server side issue.

In my particular case (node.js - express) was the order of the filter, the CORS filter (dev environment) was added after the handler for this particular request, so the server wasn't sending the proper headers and thus the browser wasn't allowing the request to take place (there was no call to the server whatsoever).

@Avto9711 if you have a similar problem, you'll see it in the browser console. And it means you are trying to access a different URL over ajax, and that URL does not allow for that kind of interaction.

@simonardejr
Copy link

Thanks! 😁 🎉

@Flyrell
Copy link

Flyrell commented Feb 7, 2020

Hey, I created the library for intercepting authentication called axios-auth-refresh. It deals with many edge cases, prevents loops, etc.
If you have some time, please, give it a try.

@sherin80
Copy link

bro awesome

@MiloszKowalski
Copy link

Thank you so much! 😁

@ashish9342
Copy link

ashish9342 commented Feb 18, 2020

Error object:

Screenshot 2020-02-17 at 4 39 40 PM

@weiranfu
Copy link

weiranfu commented Aug 9, 2020

Great Job!!!

@lfernandogunther
Copy link

Nice, I'll try it. Thank you

@AbimaelAndrade
Copy link

good job!

@yard2010
Copy link

yard2010 commented Nov 9, 2020

Error object:

Screenshot 2020-02-17 at 4 39 40 PM

Thanks! Keep in mind that this object structure (e.g. presence of response object) depends on the error that occurred, so don't make assumptions about it.

@krebbi
Copy link

krebbi commented Mar 31, 2021

For those who just want to reload the page without any message displayed:

window.axios.interceptors.response.use(function (response) { return response; }, function (error) { if (401 === error.response.status) { window.location.reload(true); } else { return Promise.reject(error); } });

@ayush-lab
Copy link

Isn't using window.loction inefficient? Also, m not able to use any other routing. Can anyone suggest a better way? Thanks

@nickolaz
Copy link

Thanks you bro !!😎.

@thibaut-decherit
Copy link

Watch out for false positives: If you use the same Axios instance to query other domains than your back end and that domain responds with status 401 your code will trigger.

Consider using a dedicated Axios instance to query other domains, or add something like that to the if (401 === error.response.status) condition:
&& isSameOrigin(error.response.request.responseURL)

/**
 * @param {string} url
 * @return {boolean}
 */
const isSameOrigin = url => {
    return new URL(window.location.href).origin === new URL(url).origin;
}

@krebbi
Copy link

krebbi commented Feb 17, 2022

Good Point. Thanks.

@hungify
Copy link

hungify commented Feb 20, 2022

I have a question?
What should I do if the API returns the 401 error code when the password does not match?

@thibaut-decherit
Copy link

@hungpurdie You need the API to tell you that 401 is because of password mismatch specifically. In the following example the API responds 401 with a "Bad credentials." message only in that specific case:

axios.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        if (
            isSameOrigin(error.response?.request?.responseURL)
            && error.response?.status === 401
            && error.response?.data?.message !== 'Bad credentials.'
        ) {
            // Do something
        }

        return Promise.reject(error);
    }
);

@haoxi911
Copy link

In case of redirect to login page you do not fulfill the promise. You must return Promise.reject(error); after window.location

Agreed. return Promise.reject(error) needs to be called no matter what.

@yajra
Copy link
Author

yajra commented Jul 19, 2023

Gist adjusted and included the reject call. Thanks!

@HogansJoe
Copy link

Awesome, great work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment