I'm trying to set a timeout for incoming requests using a custom middleware, but no error is thrown, seems that the middleware is not called once setTimeout
expires.
Here's the code I'm trying:
app.use(async (ctx, next) => {
setTimeout(() => {
if (!ctx.headersSent) {
ctx.throw(408, `processing time toke longer than ${config.PROCESSING_TIMEOUT}, request was timedout`);
}
}, config.PROCESSING_TIMEOUT);
await next();
});
Koa (or rather node's http server) has a built-in way to control the timeout of requests.
A global timeout can be set by setting server's timeout in ms
server.timeout = config.PROCESSING_TIMEOUT;
A timeout can be specified in a specific request for Koa as follows
ctx.request.socket.setTimeout(config.PROCESSING_TIMEOUT);