npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nestjs-graceful-shutdown

v1.0.3

Published

A powerful package for gracefully shutting down NestJS applications

Downloads

101,780

Readme

Table of Contents

Description

Don't let your server hang indefinitely!

When you explicitly call app.close() or if the process receive a special system signal (such as SIGTERM) after correctly invoking enableShutdownHooks during application bootstrap (check out the NestJS docs), the server stops accepting new connections while maintaining existing ones. This leads to your server hanging indefinitely due to lingering keep-alive connections or unresponsive requests.

Powered by the robust http-terminatorlibrary and backed by NestJS's built-in shutdown hooks, nestjs-graceful-shutdown ensures graceful communication with clients currently receiving responses from your server during the shutdown process. Experience a reliable and hassle-free server shutdown with ease.

Installation

You can install the library using npm:

npm install nestjs-graceful-shutdown http-terminator

Example

To integrate nestjs-graceful-shutdown into your NestJS application, follow these steps:

  1. First, import the module with GracefulShutdownModule.forRoot(...) or GracefulShutdownModule.forRootAsync(...) into your root AppModule. (refer to the module configuration documentation below).
import { GracefulShutdownModule } from 'nestjs-graceful-shutdown';

@Module({
  imports: [GracefulShutdownModule.forRoot()],
  ...
})
class AppModule {}
  1. Next, set up graceful shutdown for your NestJS application by calling the setupGracefulShutdown(...) function.

⚠️ Warning: nestjs-graceful-shutdown will automatically enable the shutdown hooks. Avoid calling enableShutdownHooks separately in your application, as it may lead to unexpected behavior. For more information on NestJS application lifecycle, refer to the NestJS documentation.

import { setupGracefulShutdown } from 'nestjs-graceful-shutdown';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // Additional configuration for your NestJS app

  setupGracefulShutdown({ app });

  await app.listen(3000);

  // Note: Timeout is used for illustration of
  // delayed termination purposes only.
  setTimeout(() => {
    process.kill(process.pid, 'SIGTERM');
  }, 5000);
}
bootstrap();

Please note that the above code snippets demonstrate the basic setup of nestjs-graceful-shutdown in your NestJS application. Make sure to adjust the code based on your specific application requirements and configuration.

Configuration

Configuration interface

The following interface is used for GracefulShutdownModule configuration:

interface IGracefulShutdownConfigOptions {
  /**
   * Cleanup function for releasing application resources
   * during server shutdown.
   */
  cleanup?: (app: INestApplication, signal?: string) => any;
  /**
   * The duration in milliseconds before forcefully
   * terminating a connection.
   * Defaults: 5000 (5 seconds).
   */
  gracefulShutdownTimeout?: number;
  /**
   * If set to `true`, the Node process will not be terminated
   * by a shutdown signal after closing all connections.
   * The shutdown behavior is identical to invoking `app.close()`.
   * Defaults: false.
   */
  keepNodeProcessAlive?: boolean;
}

The following interface is used for setupGracefulShutdown function parameters:

interface ISetupFunctionParams {
  /**
   * Your NestJS application.
   */
  app: INestApplication;
  /**
   * Shutdown signals that the application should listen to.
   * By default, it listens to all ShutdownSignals.
   */
  signals?: ShutdownSignal[] | string[];
}

Zero configuration

Just import GracefulShutdownModule to AppModule:

import { GracefulShutdownModule } from 'nestjs-graceful-shutdown';

@Module({
  imports: [GracefulShutdownModule.forRoot()],
  ...
})
class AppModule {}

Synchronous configuration

Use GracefulShutdownModule.forRoot method with argument of Configuration interface:

import { GracefulShutdownModule } from 'nestjs-graceful-shutdown';

@Module({
  imports: [
    GracefulShutdownModule.forRoot({
      cleanup: async (app, signal) => {
        // releasing resources
      },
      gracefulShutdownTimeout:
        Number(process.env.GRACEFUL_SHUTDOWN_TIMEOUT ?? 10000),
      keepNodeProcessAlive: true,
    })
  ],
  ...
})
class AppModule {}

Asynchronous configuration

With GracefulShutdownModule.forRootAsync you can, for example, import your ConfigModule and inject ConfigService to use it in useFactory method.

useFactory should return object with Configuration interface

Here's an example:

import { GracefulShutdownModule } from 'nestjs-graceful-shutdown';

@Injectable()
class ConfigService {
  public readonly timeout = 10000;
}

@Module({
  providers: [ConfigService],
  exports: [ConfigService]
})
class ConfigModule {}

@Module({
  imports: [
    GracefulShutdownModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (config: ConfigService) => {
        await somePromise();
        return {
          gracefulShutdownTimeout: config.timeout,
        };
      }
    })
  ],
  ...
})
class AppModule {}

Testing Instructions

When testing, you may need to override the graceful shutdown module with a mock module. Thanks to NestJS, this can easily be achieved using overrideModule. See the following example:

const moduleFixture: TestingModule = await Test.createTestingModule({
  imports: [AppModule],
})
  .overrideModule(GracefulShutdownModule)
  .useModule(MockModule)
  .compile();

If you don't want to use a MockModule, you can use app.listen() instead of app.init() in your test file.

beforeEach(async () => {
  const moduleFixture: TestingModule = await Test.createTestingModule({
    imports: [AppModule],
  }).compile();

  app = moduleFixture.createNestApplication();
  setupGracefulShutdown({ app });
  await app.listen();
});

Contact and Feedback

Feel free to reach out if you have any ideas, comments, or questions.

Best regards,

Hien Nguyen Minh

License

This library is licensed under the MIT License. See the LICENSE file for more details.