Why is axios doing automatic redirects? #6924
Replies: 5 comments
-
|
Thanks @OnlineProxy-io, this is new to me. I've tried this within Axios interceptors, yet it doesn't work and is still doing two requests. I've set My code below: import axios, { isAxiosError } from "axios";
import { getAPIUrl } from "./options";
import { redirectDocument } from "react-router";
const api = axios.create({
baseURL: getAPIUrl(),
withCredentials: true,
// Also disable automatic redirects since it's a SPA. We must listen to backend when to
// redirect to the login page when unauthenticated.
maxRedirects: 0,
});
api.interceptors.response.use(
(response) => {
return response;
},
(error) => {
if (isAxiosError(error)) {
if (error.response?.data?.location) {
redirectDocument(error.response.data.location);
} else {
throw error;
}
} else {
return Promise.reject(new Error(`Unprocessed Axios error in interceptor found: ${error.toString()}`));
}
},
);
export default api; |
Beta Was this translation helpful? Give feedback.
-
|
One interesting discovery: Axios comes with 3 adapters.
Why is XHR ignoring maxRedirects? PS: this old discussion confirms it #3924 (comment) |
Beta Was this translation helpful? Give feedback.
-
|
const api = axios.create({
baseURL: getAPIUrl(),
withCredentials: true,
adapter: 'fetch',
fetchOptions: {
redirect: 'manual'
},
validateStatus: (status) => status >= 200 && status < 400
}); |
Beta Was this translation helpful? Give feedback.
-
|
Thanks, @DigitalBrainJS, I wonder why this isn't mentioned in the official Axios documentation. It says there is maxRedirects, but not that it's limited to some adapters only. Secondly, I wonder if setting the maxRedirects to zero is a bad design idea? Because when the server tells the client to do a redirect, then the client should always follow it, no matter whether it's an SPA or not. How would you implement it on the client side properly? What do you think? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
... when it's a Single Page Application (SPA)?
In my SPA app, unauthenticated users aren't being redirected to the login page.
The longer version: when an API call returns a 302, to redirect an unauthenticated user to the login page, axios shouldn't make a subsequent call right away because, for Single Page Applications, the state is being handled on UI side. The server always returns the same index.html. Axios doesn't know whether it's an SPA or not.
I wonder if I should replace axios with the native
fetchAPI?Beta Was this translation helpful? Give feedback.
All reactions