Skip to content

NestJS module for request lifecycle management using AbortController. Handle client disconnections, timeouts, and graceful request cancellation.

License

Notifications You must be signed in to change notification settings

whytrchy/nestjs-aborter

Repository files navigation

Nest Logo

nestjs-aborter

Automatic request cancellation and timeout handling for NestJS

npm version npm downloads License: MIT Build Status Release codecov semantic-release: conventionalcommits

Stop wasting resources on abandoned requests. Automatically cancel operations when clients disconnect or requests timeout.


Why This Package?

When clients disconnect or requests timeout, your server continues processing—wasting CPU, memory, and database connections. This package automatically detects these scenarios and cancels ongoing operations, improving resource efficiency and performance under load.

Key Features:

  • ✅ Automatic AbortController injection on every request
  • ✅ Multi-level timeout control (global, per-endpoint, per-operation)
  • ✅ Client disconnect detection
  • ✅ Zero dependencies, full TypeScript support

Installation

npm install nestjs-aborter

Quick Start

1. Setup Module

Register the module globally and add the interceptor:

import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { AborterModule, AborterInterceptor } from 'nestjs-aborter';

@Module({
  imports: [
    AborterModule.forRoot({
      timeout: 30000, // Global 30s timeout
      skipRoutes: ['/health'], // Optional: skip specific routes
    }),
  ],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: AborterInterceptor,
    },
  ],
})
export class AppModule {}

2. Use in Controllers

Inject the AbortSignal into your route handlers and pass it to operations:

import { Controller, Get, Post } from '@nestjs/common';
import { AborterSignal, withAbort, RequestTimeout } from 'nestjs-aborter';

@Controller('users')
export class UserController {
  @Get()
  async findAll(@AborterSignal() signal: AbortSignal) {
    // Pass signal to external APIs
    const response = await fetch('https://api.example.com/users', { signal });
    return response.json();
  }

  @Post()
  @RequestTimeout(10000) // Override global timeout for this endpoint
  async create(
    @Body() dto: CreateUserDto,
    @AborterSignal() signal: AbortSignal,
  ) {
    // Wrap promises that don't natively support AbortSignal
    return withAbort(this.userService.create(dto), signal);
  }

  @Get(':id')
  async findOne(@Param('id') id: string, @AborterSignal() signal: AbortSignal) {
    // Set timeout for specific operations
    return withAbort(this.userService.findById(id), signal, { timeout: 5000 });
  }
}

Configuration Options

AborterModule.forRoot({
  timeout: 30000, // Global timeout in milliseconds (optional)
  reason: 'Request cancelled', // Custom abort reason
  enableLogging: true, // Log abort events for debugging
  skipRoutes: ['^/health$'], // Regex patterns for routes to skip
  skipMethods: ['OPTIONS'], // HTTP methods to skip
});

Async configuration with dependency injection:

AborterModule.forRootAsync({
  inject: [ConfigService],
  useFactory: (config: ConfigService) => ({
    timeout: config.get('REQUEST_TIMEOUT'),
  }),
});

Timeout Hierarchy

Timeouts are applied in priority order, with more specific timeouts overriding general ones:

// 1. Global timeout (set in module config)
AborterModule.forRoot({ timeout: 30000 })

// 2. Endpoint timeout (overrides global)
@Get() @RequestTimeout(10000) handler() {}

// 3. Operation timeout (overrides both)
withAbort(promise, signal, { timeout: 5000 })

Example combining all three levels:

@Get('dashboard')
@RequestTimeout(15000) // Max 15s for entire endpoint
async getDashboard(@AborterSignal() signal: AbortSignal) {
  // This operation has max 2s
  const quick = await withAbort(this.fastApi(), signal, { timeout: 2000 });

  // This operation has max 8s
  const slow = await withAbort(this.slowApi(), signal, { timeout: 8000 });

  return { quick, slow };
}

API Reference

Decorators

@AborterSignal() - Injects the AbortSignal for the current request

async handler(@AborterSignal() signal: AbortSignal) { }

@RequestTimeout(milliseconds) - Overrides the global timeout for a specific endpoint

@Get()
@RequestTimeout(5000) // 5 second timeout
async handler() { }

@Post('upload')
@RequestTimeout(null) // Disable timeout entirely
async upload() { }

@AborterReason() - Injects the abort reason if the request was aborted

async handler(@AborterReason() reason?: string) { }

Utilities

withAbort<T>(promise, signal?, options?) - Wraps any promise with abort capability

// Basic usage
await withAbort(someOperation(), signal);

// With custom timeout
await withAbort(someOperation(), signal, { timeout: 3000 });

AbortError - Error thrown when operations are aborted

try {
  await withAbort(operation(), signal);
} catch (error) {
  if (error instanceof AbortError) {
    console.log('Aborted:', error.message);
  }
}

Guards & Filters

AborterGuard - Prevents execution if the request is already aborted

@UseGuards(AborterGuard)
export class ApiController {}

AborterFilter - Handles timeout exceptions and returns proper HTTP status codes

@Module({
  providers: [
    { provide: APP_FILTER, useClass: AborterFilter },
  ],
})

Returns:

  • 408 Request Timeout when operation exceeds timeout
  • 499 Client Closed Request when client disconnects

Common Patterns

External API Calls

Pass the signal to any HTTP client that supports it:

await fetch(url, { signal });
await axios.get(url, { signal });

Database Operations

Wrap database queries to prevent wasted resources:

async findById(id: string, signal: AbortSignal) {
  return withAbort(
    this.prisma.user.findUnique({ where: { id } }),
    signal,
    { timeout: 3000 }
  );
}

Parallel Operations

All operations abort together when timeout is reached:

@Get('dashboard')
async getDashboard(@AborterSignal() signal: AbortSignal) {
  return Promise.all([
    withAbort(this.userService.getUsers(), signal),
    withAbort(this.postService.getPosts(), signal),
  ]);
}

Request-Scoped Services

Access the signal without manually passing it through service layers:

@Injectable({ scope: Scope.REQUEST })
export class DataService {
  constructor(@Inject(REQUEST) private request: RequestWithAbortController) {}

  async process() {
    const signal = this.request.abortController.signal;
    return withAbort(this.heavyOperation(), signal);
  }
}

Useful when you have deep service chains and don't want to pass the signal manually.

Testing

it('should handle aborted requests', async () => {
  const controller = new AbortController();
  controller.abort();

  await expect(userController.findAll(controller.signal)).rejects.toThrow(
    AbortError,
  );
});

Best Practices

  • ✅ Always pass the signal to external API calls and long-running operations
  • ✅ Use withAbort() for promises that don't natively support AbortSignal
  • ✅ Set global timeout as a safety net, endpoint timeouts for specific routes, and operation timeouts for critical calls
  • ✅ Skip health checks and monitoring endpoints in configuration to reduce overhead
  • ✅ Use AborterFilter for consistent error handling

License

MIT © whytrchy


GitHubIssuesnpm

About

NestJS module for request lifecycle management using AbortController. Handle client disconnections, timeouts, and graceful request cancellation.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •