Sling Academy
Home/Node.js/How to Set Custom Status Codes in Express.js

How to Set Custom Status Codes in Express.js

Last updated: December 28, 2023

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!

Next Article: How to Download a File from NodeJS Server using Express

Previous Article: How to Block IP Addresses in Express.js

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates