What Is This?
The HTTP 401 Unauthorized status code indicates that the request requires authentication and the client failed to provide valid credentials. The response must include a WWW-Authenticate header describing the authentication method. 401 is specifically about missing or invalid authentication — not about insufficient permissions (which is 403 Forbidden).
Common Causes & Solutions
Common Cause
Missing Authorization header in the request
Common Cause
Invalid or expired JWT token
Common Cause
Incorrect API key or bearer token
Common Cause
Session cookie missing or expired
Include correct authentication headers
Ensure your client sends the proper Authorization header for the authentication scheme being used.
// Bearer token authentication (JWT)
const token = 'eyJhbGciOiJIUzI1NiIs...'
const response = await fetch('/api/protected', {
headers: {
'Authorization': `Bearer ${token}`
}
})
if (response.status === 401) {
// Token expired or invalid — redirect to login
window.location.href = '/login'
}Implement proper token refresh
When access tokens expire, use a refresh token mechanism to obtain new tokens without requiring the user to log in again.
// Token refresh pattern
async function fetchWithRefresh(url, options = {}) {
let response = await fetch(url, options)
if (response.status === 401) {
const refresh = await fetch('/api/auth/refresh', { method: 'POST' })
if (refresh.ok) {
const { token } = await refresh.json()
options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` }
response = await fetch(url, options)
}
}
return response
}Related Entries
More from this reference:
400 400 Bad Request
The server cannot process the request due to client-side input errors.
403 403 Forbidden
The client is authenticated but does not have permission to access the resource.
404 404 Not Found
The requested resource could not be found on the server.
405 405 Method Not Allowed
The HTTP method used is not allowed for this resource.
408 408 Request Timeout
The server timed out waiting for the client to send the complete request.
413 413 Payload Too Large
The request body exceeds the server's maximum allowed size.
422 422 Unprocessable Entity
The request has valid syntax but contains semantic validation errors.
429 429 Too Many Requests
The client has exceeded the rate limit and should slow down.
Frequently Asked Questions
What is the difference between 401 and 403?
401 means authentication is missing or invalid (you are not logged in or your token is bad). 403 means authentication succeeded but you do not have permission to access the resource (you are logged in but not an admin).
What is the WWW-Authenticate header?
The WWW-Authenticate header tells the client what authentication scheme to use. Common values include Bearer (for JWT), Basic (for username/password), and Digest. The server must include this header in 401 responses.