HTTP Status Codes

401 401 Unauthorized

Authentication is required but was missing or invalid.

What Is This?

The HTTP 401 Unauthorized status code indicates that the request requires authentication and the client failed to provide valid credentials. The response must include a WWW-Authenticate header describing the authentication method. 401 is specifically about missing or invalid authentication — not about insufficient permissions (which is 403 Forbidden).

Common Causes & Solutions

1

Common Cause

Missing Authorization header in the request

2

Common Cause

Invalid or expired JWT token

3

Common Cause

Incorrect API key or bearer token

4

Common Cause

Session cookie missing or expired

5

Include correct authentication headers

Ensure your client sends the proper Authorization header for the authentication scheme being used.

// Bearer token authentication (JWT)
const token = 'eyJhbGciOiJIUzI1NiIs...'
const response = await fetch('/api/protected', {
  headers: {
    'Authorization': `Bearer ${token}`
  }
})

if (response.status === 401) {
  // Token expired or invalid — redirect to login
  window.location.href = '/login'
}
6

Implement proper token refresh

When access tokens expire, use a refresh token mechanism to obtain new tokens without requiring the user to log in again.

// Token refresh pattern
async function fetchWithRefresh(url, options = {}) {
  let response = await fetch(url, options)
  if (response.status === 401) {
    const refresh = await fetch('/api/auth/refresh', { method: 'POST' })
    if (refresh.ok) {
      const { token } = await refresh.json()
      options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` }
      response = await fetch(url, options)
    }
  }
  return response
}

Related Entries

More from this reference:

Frequently Asked Questions

What is the difference between 401 and 403?

401 means authentication is missing or invalid (you are not logged in or your token is bad). 403 means authentication succeeded but you do not have permission to access the resource (you are logged in but not an admin).

What is the WWW-Authenticate header?

The WWW-Authenticate header tells the client what authentication scheme to use. Common values include Bearer (for JWT), Basic (for username/password), and Digest. The server must include this header in 401 responses.