Common causes
- No
Authorizationheader was sent, or it's missing the scheme: it must beAuthorization: Bearer <token>, not just the token. - The token has expired. Decode it and compare the
expclaim with the current time. - The token was issued for another API or environment, so its
audorissclaim doesn't match, or it was signed with a key this server doesn't trust. - Cookies weren't sent with a cross-origin request.
fetchneedscredentials: "include", and the cookie needsSameSite=None; Secure. - The server requires authentication on CORS preflight requests. Browsers never send credentials with
OPTIONSpreflights, so the server must answer them without checking auth. - The clocks on two servers differ, so a fresh token looks like it's not yet valid or already expired.
Debugging steps
- In your browser's network tab, open the failing request and check that the
Authorizationheader or the cookie is actually there. - Paste the token into the JWT decoder and check
exp,audandiss. - Repeat the request with curl and the same token. If curl works, the difference is in how the browser sends it, often CORS or cookies.
- Read the
WWW-Authenticateheader in the response. With OAuth it often says why, for exampleerror="invalid_token".
Refresh an expired token and retry once
async function apiFetch(url, options = {}) {
const send = () => fetch(url, { ...options, headers: { ...options.headers, Authorization: `Bearer ${getAccessToken()}` } });
let response = await send();
if (response.status === 401) {
await refreshAccessToken(); // your auth library's refresh call
response = await send();
}
return response;
}Frequently asked questions
What is the difference between 401 and 403?
401 means the server doesn't know who you are, or your credentials are invalid. 403 means it knows who you are and you aren't allowed. Logging in can fix a 401 but not a 403.
Why do I get 401 only in the browser?
Usually because of CORS or cookies: the browser didn't send the credentials, or the preflight OPTIONS request was rejected because it had no auth header.
Should an API return 401 or 404 for a missing token on a private resource?
Return 401 for a missing or invalid token. Use 404 only when you want to hide whether a resource exists from users who are logged in but not allowed to see it.
More http status code lookup guides
- 502 Bad Gateway: What It Means and How to Fix It
- 504 Gateway Timeout: Causes and Fixes
- 429 Too Many Requests: Meaning, Retry-After and Fixes
- 403 Forbidden: Meaning, Causes and How to Fix It
- 500 Internal Server Error: Causes and How to Fix It
- 503 Service Unavailable: Causes and Fixes
- 400 Bad Request: Causes and Fixes (Including Cookie Too Large)
- 404 Not Found: What It Means and How to Fix It
- 301 Moved Permanently: Meaning, SEO and Examples
- 302 Found: Temporary Redirects Explained
- 408 Request Timeout: Causes and How to Fix It