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 { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
javascript
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
typescript
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, filter, take, switchMap } from 'rxjs/operators';
Refreshing auth tokens in an Angular interceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; import { GqlExecutionContext } from '@nestjs/graphql'; import { Reflector } from '@nestjs/core'; import { JwtService } from '@nestjs/jwt';
How a GraphQL auth guard works in NestJS
authentication
authorization
jwt
Intermediate
7 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void; export function observeResize(callback: ResizeCallback, delay = 150) { let timeoutId: ReturnType<typeof setTimeout> | undefined;
Debouncing window resize in TypeScript
debounce
closures
event-listeners
Intermediate
6 steps
typescript
import { Injectable, Logger, OnApplicationShutdown } from '@nestjs/common'; import { InjectRedis } from '@nestjs-modules/ioredis'; import Redis from 'ioredis'; import { DataSource } from 'typeorm';
Graceful shutdown hooks in NestJS
graceful-shutdown
lifecycle-hooks
dependency-injection
Intermediate
7 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.