Course contentsShow
← Web Development
Lesson 1657 of 2,98230. Web Authorization PatternsFree lesson

Understanding 401 Unauthorized

Learn what a 401 status code means, when servers send it, and why it indicates authentication is required or invalid.

Understanding 401 Unauthorized

What you'll learn: You'll learn what a 401 HTTP status code means, when servers send it, and why it signals missing or invalid authentication credentials.


What Does 401 Mean?

A 401 Unauthorized status code is the server's way of saying: "I don't know who you are, or your credentials are invalid." Despite the name "Unauthorized," this status actually concerns authentication, not authorization (which uses 403 Forbidden).

Think of it like a bouncer at a club: a 401 is when they won't let you in because you didn't show ID or your ID is expired. A 403 would be showing valid ID but not being on the VIP list.

When Do Servers Send 401?

Servers return a 401 response in these scenarios:

  • No credentials provided – You tried accessing a protected resource without sending an access token, JWT, or session cookie
  • Invalid credentials – Your token is malformed, expired, or doesn't match server records
  • Revoked access – Your session was invalidated or token was revoked

What Should Your Frontend Do?

When you receive a 401:

  1. Attempt token refresh – If using refresh tokens, try obtaining a new access token silently
  2. Redirect to login – If refresh fails or isn't available, send the user to the login page
  3. Clear stored credentials – Remove invalid tokens from storage to prevent repeated failed requests

A 401 is different from network errors or 500 errors—it specifically means the authentication layer rejected your request.

Example Response

A server might respond:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api"

Key Takeaway: A 401 status code means authentication failed or is missing; your frontend should attempt token refresh or redirect users to log in again.