NestJS tip: how to change HTTP server timeouts
Micael Levi L. C.

Micael Levi L. C. @micalevisk

About: just run $ npx micael

Location:
Brazil
Joined:
Sep 8, 2018

NestJS tip: how to change HTTP server timeouts

Publish Date: Apr 7 '24
24 2

What

If you don't know what those HTTP timeouts are, I recommend you to read the following articles:

How

When using the NestJS framework, sometimes you may need to change some default timeout. You can define them just like you'd do in a plain Node.js HTTP server like so:

import * as http from 'http'
import { NestFactory } from '@nestjs/core'
// import { FastifyAdapter  } from '@nestjs/platform-fastify'
import { AppModule } from './app.module'

async function bootstrap() {
  const app = await NestFactory.create(AppModule)
  // const app = await NestFactory.create(AppModule, new FastifyAdapter())

  const server = app.getHttpServer()

  console.log(server instanceof http.Server) // true

  // The timeout value for sockets
  server.setTimeout(2 * 60 * 1000)
  // The number of milliseconds of inactivity a server needs to wait for additional incoming data
  server.keepAliveTimeout = 30000
  // Limit the amount of time the parser will wait to receive the complete HTTP headers
  server.headersTimeout = 31000

  await app.listen(3000)
}
bootstrap()
Enter fullscreen mode Exit fullscreen mode

That's all!

Here you can find all the docs about the http.server we used above:

Comments 2 total

  • Костя Третяк
    Костя ТретякApr 7, 2024

    It is a little more correct to configure the server before it starts listening for HTTP requests.

    • Micael Levi L. C.
      Micael Levi L. C.Apr 7, 2024

      to be honest I thought that the 'listen' is invoked only in the next tick, so changing the server after that line shouldn't matter. I edit the post so it works as expected now.

Add comment