Axios returns 401 from a React app but the login works elsewhere
AxiosError: Request failed with status code 401Short answer
A 401 means the server received the request without valid credentials. With axios in React, the usual reasons are that the Authorization header was never attached to that request, that axios's auth option replaced your Bearer header, or that a cross-site request left out cookies because withCredentials is off.
Fix it fast
1Find out which cause you have
Open the Network tab, click the failing request, and look at the request headers. Is there an Authorization header or a Cookie header, and what does the response WWW-Authenticate header ask for?
# same call outside the browser, with the token you expect to be sent curl -i https://api.example.com/profile -H "Authorization: Bearer $TOKEN"2Match what you see, then jump to its fix
- 1
No Authorization line in the request headers of the failing call, while the token exists in storageThe Authorization header was never attached to this requestFix - 2
The request sends an Authorization: Basic header, or your Bearer value is missing, although you set oneThe auth option overwrites your Authorization headerFix - 3
The app logs in through cookies, and requests to the API on another domain or port have no Cookie headerA cross-site request does not send the session cookieFix
- 1
What does the error look like?
AxiosError: Request failed with status code 401Error: Request failed with status code 401GET https://api.example.com/profile 401 (Unauthorized)
Cause 1 of 3
The Authorization header was never attached to this request
1Check
A header set on an instance at creation time is read once. If the token did not exist yet at that moment (before login), every later request goes out without it.
grep -rn "axios.create" src/
grep -rn "Authorization" src/2Fix
Attach the header in a request interceptor, so the token is read when each request is made.
const api = axios.create({ baseURL: import.meta.env.VITE_API_URL });
api.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if (token) config.headers.set('Authorization', `Bearer ${token}`);
return config;
});3Verify
Repeat the action and confirm the Authorization header now shows in the Network tab.
// DevTools > Network > the request > Headers > Request HeadersConfirmed by axios.rest
Cause 2 of 3
The auth option overwrites your Authorization header
1Check
axios's auth option adds HTTP Basic credentials and replaces any Authorization header you set by hand. It only supports Basic, not Bearer.
grep -rn "auth:" src/2Fix
For a Bearer or API token, remove the auth option and send the token as a header. Keep auth only for a server that expects Basic credentials.
// wrong for a Bearer API
axios.get('/profile', { auth: { username: 'u', password: token } });
// right
axios.get('/profile', { headers: { Authorization: `Bearer ${token}` } });3Verify
The request headers now show Authorization: Bearer followed by your token.
// DevTools > Network > the request > HeadersConfirmed by axios.rest
Cause 3 of 3
A cross-site request does not send the session cookie
1Check
By default a browser does not include cookies or authentication headers on cross-site requests made with XMLHttpRequest, which axios uses in the browser. The setting that changes this is withCredentials.
grep -rn "withCredentials" src/2Fix
Set withCredentials to true on the instance. The API must then answer with Access-Control-Allow-Credentials: true and name your exact origin, not a wildcard.
const api = axios.create({
baseURL: 'https://api.example.com',
withCredentials: true,
});3Verify
The failing request now carries a Cookie header, and the response is 200.
// DevTools > Network > the request > Headers > Request Headers > CookieConfirmed by developer.mozilla.org
How do I stop it coming back?
- Create one axios instance for the API and attach credentials in a single request interceptor.
- Handle 401 in a response interceptor, so one place clears the stale token and sends the user to login.
- Read the 401 response headers: WWW-Authenticate names the scheme the server expects.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
Related fixes
Web apps
React shows Attempted import error when importing a component or function
Attempted import error:
The build found the file but not the name you asked for.
2 causes, each with a fixWeb apps
AxiosError Network Error with code ERR_NETWORK in a React app
Network Error
ERR_NETWORK means the request produced no readable response.
4 causes, each with a fixWeb apps
Axios get works with a URL string but ignores the object passed as the second argument
The server log shows a GET with no query string
axios.get takes a URL and an optional config object.
3 causes, each with a fixWeb apps
Can't resolve '../axios' in a React project
Module not found: Error: Can't resolve '../axios'
A path that starts with ./ or ../ is a file path, not the axios package.
3 causes, each with a fixWeb apps
An axios call never finishes when the API server stops answering
code: 'ECONNABORTED'
Axios has no timeout unless you give it one: the default is 0, which means wait forever.
3 causes, each with a fixWeb apps
Axios sends no cookie to an Express API even with withCredentials set to true
The login response has a Set-Cookie header, but the browser stores nothing
withCredentials only tells the browser to attach cookies.
4 causes, each with a fix