Project Description
I'm working on a NodeJS/Express application that, on loading the home page, uses Fetch to call a route that makes an API request. The data retrieved from the API request is returned to the client into a dropdown.
Problem
The API request often takes longer than 2 minutes to return a response, which causes Fetch to timeout with a 504 Gateway Timeout. It's my understanding the default timeout for Express is 2 minutes, so I've tried numerous ways to increase this timeout but have had no luck. It may be worth noting that I only get these timeout errors when testing the deployed code. When I test by running the code locally, I get no errors, and the 2 minute timeout does not appear to exist. Enforcing a timeout using some of the attempts below would cause a timeout when running locally.
Fix Attempts
Using the Express connect-timeout middleware as described here. I tested as a top-level middleware, and within the route itself.
Setting the server timeout after the app.listen() function:
var server = app.listen(port, () => console.log(`Listening on port ${port}...`)); server.setTimeout(3 * 60 * 1000);
Setting the keepAliveTimeout and headersTimeout after the app.listen() function:
var server = app.listen(port, () => console.log(`Listening on port ${port}...`)); server.keepAliveTimeout = 30000; server.headersTimeout = 31000;
Setting the request timeout within the route called from Fetch:
router.post('/example', function (req, res) { req.setTimeout(3 * 60 * 1000); // Call function that makes API request return res.send(api_response_data); });
Stack Overflow Threads Used
How to set the HTTP Keep-Alive timeout in a nodejs server
How to modify the nodejs request default timeout time?
Express.js connect timeout vs server timeout
Express.js HTTP request timeout
Most of the attempts listed above are reflected in these threads; however, I tried almost all suggestions found these threads as well.