Skip to content

How to Fix HTTP 401 Unauthorized Error

DodaTech Updated 2026-06-24 3 min read

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

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead 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

### What is the difference between 401 Unauthorized and 403 Forbidden?

401 means the client is not authenticated (no valid credentials). 403 means the client is authenticated but lacks permission for the resource. You need a valid login for 401; you need permissions for 403.

Can a 401 be returned for a missing or invalid API key?

Yes. Many APIs return 401 when the API key is missing, invalid, or expired. Check that the key is included in the correct header and is not expired.

How do I find expired or invalid tokens in my system?

Check the API server logs for the specific token or user ID. Use a JWT debugger to decode and inspect the token's exp (expiry) and iss (issuer) claims.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro