Categories
JavaScript Answers

How to add a response timeout with Express.js and Node.js?

Spread the love

Sometimes, we want to add a response timeout with Express.js and Node.js.

In this article, we’ll look at how to add a response timeout with Express.js and Node.js.

How to add a response timeout with Express.js and Node.js?

To add a response timeout with Express.js and Node.js, we can use the connect-timeout module.

To install it, we run

npm i connect-timeout

Then we use it by writing

const timeout = require('connect-timeout');

const haltOnTimedout = (req, res, next) => {
  if (!req.timedout) {
    next();
  }
}
app.use(timeout(120000));
app.use(haltOnTimedout);

to define the haltOnTimeout function.

We check if the request has timed out with req.timedout.

If it’s false, then we call next to call the next middleware.

And we add the middleware returned by timeout called with the request timeout in milliseconds and the halfOnTimedout function with app.use in the order they’re listed to lets us set a timeout for all requests to 120000 milliseconds.

Conclusion

To add a response timeout with Express.js and Node.js, we can use the connect-timeout module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *