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 🙏

© 2025 – Pkg Stats / Ryan Hefner

nestjs-aborter

v1.0.1

Published

Automatic request cancellation and timeout handling for NestJS applications

Downloads

166

Readme

nestjs-aborter

Automatic request cancellation and timeout handling for NestJS

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

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