401 Unauthorized
Despite its name, 401 is really about authentication, not authorization. It means the client must authenticate itself to get the response. The server's response should include a WWW-Authenticate header telling the client how to authenticate. If you're already authenticated but lack permission, 403 is the right code.
What can I do?
- Try logging out and logging back in.
- If using an API, check your API key is correct and not expired.
- Clear your browser cookies and try again.
How to debug & fix
- Always include WWW-Authenticate header in 401 responses
- Return 401 when no/invalid credentials; 403 when authenticated but not authorized
- Implement token refresh logic — return 401 specifically when the token has expired so clients can refresh
- Check token expiry: return 401 specifically for expired tokens so clients can trigger refresh; use 403 for revoked tokens.
- Always include WWW-Authenticate header — it is required by RFC 9110.
Code Example
const auth = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401)
.set('WWW-Authenticate', 'Bearer realm="api"')
.json({ error: 'Authentication required' });
}
try { req.user = verify(token, SECRET); next(); }
catch { res.status(401).json({ error: 'Invalid or expired token' }); }
};
Related Status Codes
How HTTP Status Codes Work
Every HTTP response carries a three-digit status code that tells the client — browser, API consumer, or search-engine crawler — exactly what happened. The first digit defines the class: 1xx informational (request in progress), 2xx success, 3xx redirection, 4xx client error (bad request, missing auth, not found), and 5xx server failure.
Status codes are standardised in RFC 9110 (HTTP Semantics, 2022). Extensions like WebDAV (RFC 4918) and rate-limit headers (RFC 6585) added codes beyond the core set. When a client receives an unrecognised code, the rule is to treat it as the generic x00 of its class.
Why the Right Code Matters
Semantically correct codes help search engines index accurately (301 passes link equity; 410 removes pages faster than 404), allow API clients to implement correct retry logic (429 + Retry-After, 503 + Retry-After), and let monitoring systems distinguish bugs (500) from load issues (503) from auth failures (401/403).
Looking up a different status code? The full reference covers all HTTP codes with causes, fix guides, and copyable code examples for Node.js and Python.
Browse the full HTTP Status Code reference →