How to Fix HTTP 401 Unauthorized Error
In this tutorial, you'll learn about How to Fix HTTP 401 Unauthorized Error. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your API client receives:
HTTP/1.1 401 Unauthorized
Or:
401 Unauthorized: Authentication is required and has failed or not been provided.
The request lacks valid authentication credentials or the provided credentials are invalid or expired.
Quick Fix
1. Check the Authorization header format
APIs typically expect a Bearer token or Basic auth:
// Wrong — missing header
fetch('/api/users')
// Wrong — wrong format
fetch('/api/users', {
headers: { 'Authorization': 'token abc123' }
})
// Right — Bearer token
fetch('/api/users', {
headers: { 'Authorization': 'Bearer abc123' }
})
2. Verify the token is not expired
JWTs or other tokens may have expired. Check the expiry:
# Decode a JWT to see expiry
echo "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MTkyMDAwMDB9.signature" | cut -d. -f2 | base64 -d 2>/dev/null || true
If expired, refresh the token:
// Refresh token flow
const refreshResponse = await fetch('/api/auth/refresh', {
method: 'POST',
headers: { 'Authorization': `Bearer ${refreshToken}` }
})
const { accessToken } = await refreshResponse.json()
3. Check the API key header name
Different APIs use different header names:
// Wrong — wrong header name
fetch('/api/data', {
headers: { 'x-api-key': 'abc123' }
})
// Right — check API docs for the correct header
fetch('/api/data', {
headers: { 'X-API-Key': 'abc123' }
})
4. Check Basic auth encoding
Basic auth requires Base64 encoding of username:password:
// Wrong — raw credentials
fetch('/api/data', {
headers: { 'Authorization': 'Basic admin:password123' }
})
// Right — Base64 encoded
const encoded = btoa('admin:password123')
fetch('/api/data', {
headers: { 'Authorization': `Basic ${encoded}` }
})
5. Debug with curl
# Test with Bearer token
curl -v -H "Authorization: Bearer abc123" https://api.example.com/users
# Test with Basic auth
curl -v -u admin:password123 https://api.example.com/users
Prevention
- Use environment variables to store API keys and tokens.
- Implement automatic token refresh before expiry.
- Log authentication failures with enough context to debug.
- Use short-lived access tokens with long-lived refresh tokens.
- Always check the API documentation for the exact auth mechanism.
Common Mistakes with 401 unauthorized
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world API code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro