Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
Stop express router callback function execution on timeout

I need to define a timeout for specific routes in Express so that instead of getting a server default timeout error, my API returns JSON data. I add it like this to the beginning of the router.get callback function

    router.get('/', function (req, res, next) {
      res.setTimeout(10000, function () {
         res.status(500).json({ error: 'Response Processing Timed Out.' });
      });
      /*
       some time-consuming code here
      */
     res.json(result); //this should never happen if timeout occurs 
    });

and that (timeout part) works OK (it returns JSON error message to the client on timeout, as expected).

The problem is that the rest of the code is still executed and when it gets to the regular res.json method - res.json(result) I get the error ERR_HTTP_HEADERS_SENT (as it should be, because it tries to do another res.json after the one containing the error message has already been sent)

If that was an ordinary check for errors I would add a return statement after res.json, but it is not - it is inside a callback function and a return would just end the callback, but not the parent function (in this case router.get callback function). I know that I could set some variable to true when timeout occurs and then check if it is true before any res.json, but I'd like to avoid that (I have quite a few res.json lines in the function, and also I'd like to avoid executing time-consuming code if the error message has already been sent)

Any ideas on how to solve this? If res.setTimeout is not the proper way, I'll be glad to learn the right way to do this.

Thanks

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!