typescript
45 lines · 8 steps
A per-route timeout interceptor in NestJS
A NestJS interceptor that aborts slow requests using a metadata-driven, per-handler timeout and returns a clean HTTP error.
Explained by
highlit
1import {
2 Injectable,
3 NestInterceptor,
4 ExecutionContext,
5 CallHandler,
6 RequestTimeoutException,
7 Logger,
8} from '@nestjs/common';
9import { Reflector } from '@nestjs/core';
10import { Observable, throwError, TimeoutError } from 'rxjs';
11import { catchError, timeout } from 'rxjs/operators';
12
13export const REQUEST_TIMEOUT_KEY = 'request_timeout_ms';
14
15@Injectable()
16export class TimeoutInterceptor implements NestInterceptor {
17 private readonly logger = new Logger(TimeoutInterceptor.name);
18 private readonly defaultTimeout = 5000;
19
20 constructor(private readonly reflector: Reflector) {}
21
22 intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
23 const timeoutMs =
24 this.reflector.getAllAndOverride<number>(REQUEST_TIMEOUT_KEY, [
25 context.getHandler(),
26 context.getClass(),
27 ]) ?? this.defaultTimeout;
28
29 return next.handle().pipe(
30 timeout(timeoutMs),
31 catchError((err) => {
32 if (err instanceof TimeoutError) {
33 const request = context.switchToHttp().getRequest();
34 this.logger.warn(
35 `${request.method} ${request.url} exceeded ${timeoutMs}ms`,
36 );
37 return throwError(
38 () => new RequestTimeoutException('Request processing timed out'),
39 );
40 }
41 return throwError(() => err);
42 }),
43 );
44 }
45}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Interceptors can wrap the response stream to enforce cross-cutting concerns like timeouts without touching handler code.
- 2Reflector.getAllAndOverride lets a route-level decorator override a class-level or default value cleanly.
- 3Translating an RxJS TimeoutError into a domain exception keeps clients from leaking internal error shapes.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-per-route-timeout-interceptor-in-nestjs-explained-typescript-b4d2/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.