What It Means
Despite its name, 401 Unauthorized is actually about authentication, not authorization. It means: "I don't know who you are. Please identify yourself." The server wants credentials — a login token, API key, or session cookie — before it will respond.
401 vs 403
| Code | Meaning | Fix |
|---|---|---|
| 401 | Not authenticated — no valid credentials | Log in / provide API key |
| 403 | Authenticated but not authorized — you don't have permission | Request access from admin |
Example: A 401 is getting stopped at the front door because you have no ID. A 403 is being told "your ID is valid but you're not allowed in this section."
Handling 401 in JavaScript
async function apiRequest(url, options = {}) {
const token = localStorage.getItem('auth_token');
const res = await fetch(url, {
...options,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
...options.headers
}
});
if (res.status === 401) {
// Token expired or invalid — redirect to login
localStorage.removeItem('auth_token');
window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname);
return;
}
return res.json();
}
WWW-Authenticate Header
A proper 401 response includes a WWW-Authenticate header that tells the client what type of authentication is required:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api", error="invalid_token"
WWW-Authenticate: Basic realm="Admin Area"