How to send http response from setTimeout callback - express

Viewed 1874

I would like to have custome response time-out, so that I am trying to send the response from setTimeout callback if the processing time exceeds certain interval.

In the following example, I set 20ms as time-out period within which services.getReport() has to be processed otherwise the API has to send response as response_timed_out.

The following code works fine but it throws exception like

Cannot set headers after they are sent to the client

router.post("/getReport", (req, res) => {
  setTimeout(() => {
    res.send({ status:503, msg: "response_timed_out" });
  }, 20);
  services.getReport(req, res);
});
1 Answers

You can use setTimeout method on the request object to define timeout time for each route.

router.post("/getReport", (req, res) => {
  req.setTimeout(2000);
  services.getReport(req, res);
});

You can also define timeout time globally for all routes on the server.

const server = app.listen(port, () => {});
server.setTimeout(15000);

You can also provide the second argument which is callback that will run when timeout occurs. If you want the callback then you call setTimeout on the response.

router.post("/getReport", (req, res) => {
  res.setTimeout(2000, () => res.send('timed_out'));
  services.getReport(req, res);
});
Related