Quick start
-
Import the module in your root module.
forRoot()applies the middleware to every route.app.module.ts import { Module } from '@nestjs/common';import { AbortControllerModule } from 'nestjs-abort-controller';@Module({imports: [AbortControllerModule.forRoot({ timeout: 30_000 })],})export class AppModule {} -
Inject the signal with
@NestAbortSignal()and pass it on.users.controller.ts import { Controller, Get, Param } from '@nestjs/common';import { NestAbortSignal } from 'nestjs-abort-controller';@Controller('users')export class UsersController {@Get(':id')async findOne(@Param('id') id: string, @NestAbortSignal() signal: AbortSignal) {const res = await fetch(`https://api.example.com/users/${id}`, { signal });return res.json();}} -
Check it in loops with
throwIfAborted(), for work that does not take a signal itself.import { throwIfAborted } from 'nestjs-abort-controller';for (const item of items) {throwIfAborted(signal);await process(item);} -
Optional: proper status codes. Register
AbortExceptionFilterso a timeout becomes408instead of500.app.module.ts import { APP_FILTER } from '@nestjs/core';import { AbortControllerModule, AbortExceptionFilter } from 'nestjs-abort-controller';@Module({imports: [AbortControllerModule.forRoot()],providers: [{ provide: APP_FILTER, useClass: AbortExceptionFilter }],})export class AppModule {}
Try it
Section titled “Try it”Start the app, request a slow endpoint and press Ctrl+C before it answers:
curl localhost:3000/users/1With enableLogging: true the middleware logs Client disconnected, aborting request and the fetch above rejects
with the library’s AbortError.