Categories
JavaScript Answers

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

Spread the love

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

For instance, we write

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

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

app.use(timeout(120000));
app.use(haltOnTimedout);

to add the halfOnTimedout function.

In it, we check if the request timed out with req.timedout.

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

Then we call app.use to add the timeout middleware to make requests time out after 120000ms.

And we call app.use again to add the haltOnTimedout middleware.

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 *