Introduction

When our server responds to a request, it sends an HTTP status code. These codes tell the client what happened.

You have seen these status codes in the network tab in the browser’s dev tools.

How Express Handles Status Codes

  • res.json() automatically returns a 200 OK - This means the request was successful
  • res.status() lets you set a different status code - For example, res.status(404) for “not found”
  • You’ve already seen this in action - In our examples above, we used res.status(404).json() when a product wasn’t found

Success Codes:

  • 200 OK - Request succeeded (default for res.json())
  • 201 Created - New resource created (used for POST requests)

Client Error Codes:

  • 400 Bad Request - Invalid request data
  • 401 Unauthorised - Not logged in
  • 403 Forbidden - Logged in but not allowed
  • 404 Not Found - Resource does not exist

Server Error Codes:

  • 500 Internal Server Error - Something went wrong on the server

Using Status Codes in Your APIs

You can chain res.status() with res.json():

// Success (200 is automatic)
res.json({ message: "Success!" });

// Not found (404)
res.status(404).json({ error: "Product not found" });

// Bad request (400)
res.status(400).json({ error: "Invalid ID" });
Tags: