Skip to content
Buy me a coffee

nestjs-abort-controller

1.3 · Express + Fastify · ~3M downloads a year

Stop work
nobody is waiting for.

Every NestJS request gets an AbortSignal. It aborts when the client disconnects or the request runs past its timeout, so database queries, fetch calls and loops stop instead of finishing for nobody.

app.module.ts · report.controller.ts
@Module({
imports: [AbortControllerModule.forRoot({ timeout: 1500 })],
providers: [{ provide: APP_FILTER, useClass: AbortExceptionFilter }],
})
export class AppModule {}
@Controller('reports')
export class ReportController {
@Get()
async build(@NestAbortSignal() signal: AbortSignal) {
for (const chunk of chunks) { // 8 chunks, 250 ms each
throwIfAborted(signal); // stop as soon as nobody needs it
await this.reports.render(chunk, { signal });
}
return { ok: true };
}
}
live · real throwIfAborted, simulated request
0runtime dependencies
AbortSignalnative, per request
30 sdefault timeout
NestJS 11Express + Fastify
~136kweekly downloads

What it adds

One module. Cancellation everywhere.

Per request

Every request gets its own AbortSignal.

One middleware, registered by AbortControllerModule. The signal is a native AbortSignal: hand it to fetch, database drivers, fs/promises, timers/promises and anything else that takes one.

Read more
@Get(':id')
find(@Param('id') id: string, @NestAbortSignal() signal: AbortSignal) {
return fetch(`${API}/users/${id}`, { signal });
}
Disconnects

The client left. Stop working.

When the connection closes before the response is sent, the signal aborts. Finished responses and POST bodies never trigger it.

Read more
// abort reason
new AbortError('Client disconnected', 'client-disconnected')
Timeout

A deadline for every request.

30 seconds by default, per module or per route group. 0 turns it off. The timer is cleared when the response ends.

Read more
AbortControllerModule.forRoutes(['/reports/*path'], {
timeout: 120_000,
})
Errors

Know why it stopped.

AbortError.reason is 'timeout' or 'client-disconnected'. throwIfAborted() rethrows the middleware's own error, so the reason survives.

Read more
catch (error) {
if (error instanceof AbortError) log(error.reason);
}
Responses

408 for timeouts, silence for the gone.

The optional AbortExceptionFilter answers timeouts with 408 Request Timeout and sends nothing to a client that already left.

Read more
providers: [
{ provide: APP_FILTER, useClass: AbortExceptionFilter },
]
Anywhere

Guards, interceptors and Fastify too.

The controller and signal live on the Node request under symbol keys. Read them anywhere you have the request. Fastify works the same: the decorator looks in req.raw for you.

Read more
const req = context.switchToHttp().getRequest();
const signal: AbortSignal = req[ABORT_SIGNAL] ?? req.raw?.[ABORT_SIGNAL];

The toolbox

Small on purpose. The whole API fits here.

Module

  • forRoot(options?)All routes
  • forRoutes(routes, options?)Some routes
  • timeoutms, default 30000, 0 = off
  • enableLoggingDebug / warn logs

Handlers

  • @NestAbortSignal()Inject the signal
  • throwIfAborted(signal)Checkpoint in loops
  • signal.aborted · reasonNative AbortSignal

Errors

  • AbortErrorname, message, reason
  • 'timeout'Deadline hit
  • 'client-disconnected'Connection closed early
  • AbortExceptionFilter408 / no response

Low level

  • ABORT_SIGNALSymbol key on the request
  • ABORT_CONTROLLERAbort it yourself
  • AbortControllerMiddlewareApply it manually

In code

Pass the signal down. That is the whole trick.

@Injectable()
export class SearchService {
constructor(private readonly http: HttpService) {}
async search(query: string, signal: AbortSignal) {
const [a, b] = await Promise.all([
fetch(`${A}?q=${query}`, { signal }).then((r) => r.json()),
firstValueFrom(this.http.get(B, { params: { q: query }, signal })),
]);
return merge(a, b.data);
}
}

Get started

Import the module. Inject the signal.

Two lines to start. Then pass the signal to whatever does the slow work.