← Back to Chapters

401 Unauthorized

? 401 Unauthorized

? Quick Overview

The 401 Unauthorized HTTP status code indicates that the client request has not been completed because it lacks valid authentication credentials. The server requires authentication, and the client either did not provide credentials or provided invalid ones.

? Key Concepts

  • Client must authenticate to access the resource
  • Server sends a WWW-Authenticate header
  • Different from 403 Forbidden
  • Common in APIs and protected routes

? Syntax / Theory

A 401 response is returned when authentication is required and has failed or has not yet been provided. This typically happens when accessing protected resources such as dashboards, APIs, or admin panels.

? View Code Example
// Server responds with 401 when authentication fails
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="Access to admin"

? Live Output / Explanation

Server Response

The browser or client receives a 401 status and may prompt the user to log in again. In APIs, the client usually needs to resend the request with valid tokens or credentials.

? Interactive Example

See how the server responds based on your credentials below:

? View Source Logic
// JavaScript fetch example handling 401 Unauthorized
fetch("/api/profile")
.then(response => {
  if (response.status === 401) {
    throw new Error("Unauthorized access");
  }
  return response.json();
})
.catch(error => console.error(error.message));

Simulator: Enter the correct token to access the data.

Hint: The correct token is secret123

 

? Use Cases

  • Accessing protected REST APIs
  • User login/session validation
  • Token-based authentication failures
  • Expired or missing credentials

✅ Tips & Best Practices

  • Always return 401 for authentication failures
  • Include proper WWW-Authenticate headers
  • Differentiate clearly between 401 and 403
  • Handle token expiration gracefully

?️ Try It Yourself

  • Create a protected API route and test without credentials
  • Send invalid authentication headers and observe the response
  • Handle 401 errors on the frontend