Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

Axios returns 401 from a React app but the login works elsewhere

ErrorAxiosError: Request failed with status code 401

Short 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.

  • Applies to axios 1.x, React 19, Node.js 22
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 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"
  2. 2Match what you see, then jump to its fix

    1. 1No 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. 2The request sends an Authorization: Basic header, or your Bearer value is missing, although you set oneThe auth option overwrites your Authorization headerFix
    3. 3The 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

What does the error look like?

  • AxiosError: Request failed with status code 401
  • Error: Request failed with status code 401
  • GET 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 Headers

Confirmed by axios.rest

Did this fix it?

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 > Headers

Confirmed by axios.rest

Did this fix it?

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 > Cookie

Confirmed by developer.mozilla.org

Did this fix it?

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:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.