4xx Client ErrorCommonly usedRFC 9110

401Unauthorized

Authentication is required — client is not authenticated.

What it means

Despite the name "Unauthorized", this code actually means "Unauthenticated". The client must authenticate itself to get the requested response. Unlike 403, the client can retry with valid credentials.

When to use it

  • No authentication token was provided
  • Authentication token is expired
  • Authentication token is invalid or malformed
  • API key is missing

Common causes

  • Forgot to include Authorization header
  • JWT token has expired
  • Invalid or revoked API key
  • Session cookie is missing or expired

Code Examples

Express JWT middleware
javascript
const authMiddleware = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];

  if (!token) {
    return res.status(401).json({
      error: 'Authentication required',
      message: 'Please provide a valid Bearer token',
    });
  }

  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch {
    res.status(401).json({ error: 'Invalid or expired token' });
  }
};

Quick Facts

Code401
CategoryClient Error
SpecRFC 9110
CommonYes

Relevant Headers

WWW-Authenticate

Defines the authentication method that should be used

Authorization

Request header containing credentials (Bearer token, Basic auth)

Related Codes

← Back to all status codes