How to Set Custom Status Codes in Express.js

Updated: December 28, 2023 By: Guest Contributor Post a comment

Overview

Express.js is a popular web application framework for Node.js designed to build APIs and web applications easily. One of the many features it offers is the ability to control HTTP status codes that are returned to the client from your server. HTTP status codes play a significant role in RESTful APIs and web applications; they indicate the success or failure of an HTTP request. In this tutorial, you will learn how to set custom status codes in Express.js to convey the right message to the client interacting with your server.

Setting a Basic Custom Status Code

To begin, let’s set a basic custom status code. This action is achieved by using the status() method that is available on the response object in Express.js. Here is a simple example:

const express = require('express');
const app = express();

app.get('/not-found', (req, res) => {
  res.status(404).send('Page not found');
});

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

Advanced Custom Status Codes

Now let’s get into some advanced usage. Custom status codes can also be coupled with JSON responses, error handling, and more. Below is how you can send a JSON response with a custom status code:

app.post('/create', (req, res) => {
  // Assume we have some logic to create an item
  // If something goes wrong, we send a 400 Bad Request status code
  if (errorOccurred) {
    return res.status(400).json({ error: 'Bad request' });
  }
  // If everything's okay send a 201 Created status code
  res.status(201).json({ message: 'Item created successfully' });
});

Custom Error Handling Middleware

In more complex Express.js applications, you may want to have a centralized error handling mechanism. This can be done by defining a custom error-handling middleware at the end of your middleware stack. It catches any error that occurs in your app and sets an appropriate status code:

app.use((error, req, res, next) => {
  console.error(error);
  res.status(error.status || 500).json({ error: error.message });
});

Conclusion

In conclusion, controlling HTTP response status codes is essential for good API design. This tutorial showed you how to handle status codes in Express.js, from simple use cases to more complex error handling structures. Remember to always send meaningful status codes to effectively communicate the state of the request to your clients. Happy coding!