HTTP 401 Unauthorized — Authentication vs Authorization & Fix Guide
Authentication is required and the request lacks valid credentials. Despite the name 'Unauthorized', this status means 'Unauthenticated' — the client must authenticate itself. The response must include a WWW-Authenticate header indicating the authentication scheme.
When to Return 401
Use 401 when a request requires authentication and the client provided no credentials (or the provided token is missing/invalid/expired). Include a WWW-Authenticate header. Use 403 when the client is authenticated but lacks permission.
Common Causes
- No Authorization header on a protected endpoint
- Expired JWT or session token
- Invalid token signature
- Revoked API key
- Incorrect username/password
HTTP Response Example
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api"
Content-Type: application/json
{"error": "Authentication required"}Code Examples
Express.js
const authenticateToken = (req, res, next) => {
const auth = req.headers.authorization
if (!auth?.startsWith('Bearer ')) {
return res
.set('WWW-Authenticate', 'Bearer realm="api"')
.status(401)
.json({ error: 'Authentication required' })
}
try {
req.user = verifyJwt(auth.slice(7))
next()
} catch {
res
.set('WWW-Authenticate', 'Bearer realm="api", error="invalid_token"')
.status(401)
.json({ error: 'Invalid or expired token' })
}
}Next.js App Router
// middleware.ts
export function middleware(request: NextRequest) {
const token = request.headers.get('authorization')?.replace('Bearer ', '')
if (!token) {
return new NextResponse(
JSON.stringify({ error: 'Authentication required' }),
{
status: 401,
headers: {
'Content-Type': 'application/json',
'WWW-Authenticate': 'Bearer realm="api"',
},
}
)
}
}Related Status Codes
Frequently Asked Questions
What does HTTP 401 Unauthorized mean?
Authentication is required and the request lacks valid credentials. Despite the name 'Unauthorized', this status means 'Unauthenticated' — the client must authenticate itself. The response must include a WWW-Authenticate header indicating the authentication scheme.
When should an API return 401?
Use 401 when a request requires authentication and the client provided no credentials (or the provided token is missing/invalid/expired). Include a WWW-Authenticate header. Use 403 when the client is authenticated but lacks permission.
What causes an HTTP 401 error?
Common causes: No Authorization header on a protected endpoint; Expired JWT or session token; Invalid token signature; Revoked API key; Incorrect username/password.
When should I NOT use 401?
Authorisation failures (wrong permissions) on an authenticated request — use 403 for that.
