Error Encyclopedia
401

401 Unauthorized Error

Learn what a 401 Unauthorized error means, common causes, and how to fix authentication failures in your web applications.

What Does This Error Mean?

The 401 Unauthorized status code indicates that the request lacks valid authentication credentials for the target resource. Unlike 403 Forbidden (which means the server understands who you are but denies access), 401 means the server does not know who you are or your credentials are invalid.

Common Causes

1

Missing or expired authentication token (JWT, session cookie)

2

Invalid API key or bearer token

3

Missing Authorization header

4

Token has expired and needs refresh

5

Credentials were revoked by the server

6

Wrong authentication scheme (e.g., using Basic instead of Bearer)

How to Fix It

Check the Authorization header

Verify your request includes a valid Authorization header with the correct scheme.

// ✅ Correct format for Bearer token
fetch("/api/data", {
  headers: { "Authorization": "Bearer your-jwt-token" }
})

// ✅ Correct format for Basic auth
fetch("/api/data", {
  headers: { "Authorization": "Basic " + btoa("user:pass") }
})

Refresh expired tokens

Implement token refresh logic to automatically obtain new tokens before they expire.

async function refreshToken() {
  const res = await fetch("/auth/refresh", {
    method: "POST",
    credentials: "include"
  })
  if (res.ok) {
    const { token } = await res.json()
    localStorage.setItem("token", token)
    return token
  }
  throw new Error("Session expired")
}

Include credentials for CORS requests

When making cross-origin requests, ensure credentials (cookies) are included.

fetch("https://api.example.com/data", {
  credentials: "include",
  headers: { "Authorization": `Bearer ${token}` }
})

Before & After Examples

❌ Before
GET /api/users
Response: 401 Unauthorized
{ "error": "No authorization token provided" }
✅ After
GET /api/users
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
Response: 200 OK
{ "users": [...] }

Related Tools

Use these tools to debug and fix this error:

Related Guides

Deepen your understanding with these guides and tutorials:

Related Errors

Other common errors in this category:

Frequently Asked Questions

What is the difference between 401 and 403?

401 Unauthorized means you are not authenticated (missing or invalid credentials). 403 Forbidden means you are authenticated but do not have permission to access the resource.

Why do I get 401 even with a valid token?

The token may be expired, the signature may not match (if the server uses a different secret), or the token may be for a different audience/issuer than expected.