How to Return Status Codes in Express

For any developer working with APIs and Express, understanding how to return the correct HTTP status codes is important. HTTP status codes are the server's way of communicating the status of a client's request - whether it was successful, caused a server error, or anything in between.

Many experienced developers have probably been in a situation in which they're using an API and the request is failing, but they have no idea why. If the API were to return the proper status code, along with a short message, it could save developers hours of debugging time.

In this short article, we'll dive into the importance of these status codes and how you can use them in Express.js, the fast, unopinionated, and minimalist web framework for Node.js.

Let's start off with the simplest way to return a status code in Express.js. This is done using the res.status() function, where res is the response object passed to your route handler callback.

app.get('/api/users', (req, res) => {
    res.status(200).json({ message: "Success!" });
});

In the above example, we're sending a status code of 200, which indicates that the request was successful.

However, Express.js offers a more semantic way to send many common HTTP status codes. For example, you can use res.sendStatus() instead of res.status().send() for sending status codes with a brief message.

app.get('/api/users', (req, res) => {
    res.sendStatus(200); // equivalent to res.status(200).send('OK')
});

Note: Remember that HTTP status codes aren't just for successful requests. If you're returning an error status, like 400 for a "bad request" or 404 for "not found", it's helpful to provide more information about what went wrong.

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

When dealing with errors, we can use the res.status() method in conjunction with .json() to provide a detailed error message.

app.get('/api/users', (req, res) => {
    res.status(404).json({ error: "User not found!" });
});

This way, the client will receive both the error status code and a message detailing the problem.

But how do we handle unexpected errors that occur during execution of our code? Express.js offers error-handling middleware functions for that.

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle. They can execute any code, make changes to the request and the response objects, end the request-response cycle, and call the next middleware function in the stack.

Here's a basic example of an error-handling middleware function:

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

In this example, if an error is thrown anywhere in your application, it will be caught by this middleware function. The function logs the error stack trace and sends a 500 status code to the client, indicating an internal server error.

Returning HTTP status codes in Express.js can be achieved in a few different ways. Whether it's through using res.status(), res.sendStatus(), or in combination with error-handling middleware functions, each method plays a role in communicating the state of client requests. Understanding these different methods will help us to write more robust code, but also user-friendly APIs.

By taking the time to return proper status codes, you ensure that your application communicates effectively with clients, whether they're browsers, third-party applications, or other servers.

Was this helpful?

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms