Skip to content
Buy me a coffee

Quick start

  1. 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 {}
  2. 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();
    }
    }
  3. 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);
    }
  4. Optional: proper status codes. Register AbortExceptionFilter so a timeout becomes 408 instead of 500.

    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 {}

Start the app, request a slow endpoint and press Ctrl+C before it answers:

Terminal window
curl localhost:3000/users/1

With enableLogging: true the middleware logs Client disconnected, aborting request and the fetch above rejects with the library’s AbortError.