Qaynaq LABS · TOOLS

HTTP · 4xx Client Error

401 Unauthorized

Request lacks valid authentication credentials for the target resource.

When you see this status

  • Missing or invalid Authorization header
  • Expired or revoked access token
  • Incorrect credentials in Basic/Digest auth
  • Unauthenticated API request to protected endpoint

Common causes

  • Client omits credentials entirely
  • Token expired or malformed
  • Wrong password or username
  • Missing or invalid session cookie

How to debug it

  1. Verify Authorization header presence and format
  2. Check token expiration/validity in auth provider
  3. Inspect server logs for auth middleware failures
  4. Test with valid credentials to isolate issue

Return this code in your framework

Express (Node.js)
res.status(401).send('Unauthorized');
FastAPI (Python)
from fastapi import HTTPException
raise HTTPException(status_code=401, detail="Unauthorized")
NestJS
@Get()
getData(@Request() req) {
  if (!req.user) throw new UnauthorizedException();
}
Go (net/http)
http.Error(w, "Unauthorized", http.StatusUnauthorized)

About HTTP 401

HTTP status code 401 Unauthorized is part of the 4xx Client Error family. Request lacks valid authentication credentials for the target resource. Understanding it is essential for backend engineers, API designers, and anyone debugging integrations between services.

The Qaynaq Labs HTTP Status Code Explainer covers all standard codes with practical guidance: what triggers them, how to debug them in production, and exactly how to return them from common frameworks. Each code page is hand-curated and verified.

Frequently asked

Should I return 401 or 403 for missing permissions?

Use 401 when authentication is missing/invalid, 403 when authenticated but unauthorized.

Can I include a WWW-Authenticate header with 401?

Yes, include it to specify auth schemes (e.g., Bearer) and parameters like realm.

Is 401 idempotent?

Yes, safe to retry after providing valid credentials. Server state unchanged.