🔐
401
Unauthorized
!
?

Example HTTP Response

HTTP Response
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer
Common Causes
  • Missing authentication token
  • Expired login session
  • Invalid credentials
Technical Details

What does this mean?

Who are you?! The bouncer needs to see some ID before letting you in. Time to log in!

Technical Definition

The client must authenticate itself to get the requested response.

RFC Says

"The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource."

Plain English:

You need to prove who you are before accessing this resource. Either you didn't provide credentials at all, or the ones you provided are invalid or expired.

Common Misinterpretation

Despite the name 'Unauthorized', this code is actually about authentication (proving identity), not authorization (having permission). Many developers confuse 401 with 403 - use 401 when the user hasn't logged in or their token is invalid, and 403 when they ARE logged in but don't have permission.

"The server generating a 401 response MUST send a WWW-Authenticate header field containing at least one challenge applicable to the target resource."

Plain English:

When you return a 401, you must include a WWW-Authenticate header that tells the client how to authenticate (e.g., 'Bearer' for token auth, 'Basic' for username/password).

Code Snippets

Ready-to-use code for returning this HTTP status in your application:

Node.js
// Express.js
app.get('/example', (req, res) => {
  res.status(401).json({
    error: 'Unauthorized',
    message: 'Your error message here'
  });
});

// Native HTTP
const http = require('http');

http.createServer((req, res) => {
  res.writeHead(401, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    error: 'Unauthorized',
    message: 'Your error message here'
  }));
}).listen(3000);
When to Use This Code
  • No authentication credentials provided
  • Authentication token is invalid or expired
  • User needs to log in to access the resource
  • Use 403 when user IS authenticated but lacks permission
Commonly Confused With