A timeout interceptor helps stop a request if it takes too long. This keeps your app fast and avoids waiting forever.
0
0
Timeout interceptor in NestJS
Introduction
When you want to limit how long a request can take before stopping it.
To avoid slow responses blocking other users.
When calling external services that might hang or be slow.
To improve user experience by failing fast on delays.
When you want to add a global timeout rule for all or some requests.
Syntax
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, RequestTimeoutException } from '@nestjs/common'; import { Observable, throwError, TimeoutError } from 'rxjs'; import { timeout, catchError } from 'rxjs/operators'; @Injectable() export class TimeoutInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { return next.handle().pipe( timeout(5000), // time in milliseconds catchError(err => { if (err instanceof TimeoutError) { return throwError(() => new RequestTimeoutException()); } return throwError(() => err); }), ); } }
The timeout operator sets the max wait time in milliseconds.
If the timeout happens, it throws a TimeoutError, which we catch and convert to a NestJS RequestTimeoutException.
Examples
Use this to set a 3-second timeout for the request.
NestJS
timeout(3000) // sets timeout to 3 seconds
Use this to allow a longer 10-second timeout.
NestJS
timeout(10000) // sets timeout to 10 seconds
This catches the timeout error and sends a clear message back.
NestJS
catchError(err => {
if (err instanceof TimeoutError) {
return throwError(() => new RequestTimeoutException('Request took too long'));
}
return throwError(() => err);
})Sample Program
This controller has two routes. The fast route responds quickly within the timeout. The slow route takes longer than the 5-second timeout and will cause a timeout error.
NestJS
import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { Observable, of } from 'rxjs'; import { delay } from 'rxjs/operators'; import { TimeoutInterceptor } from './timeout.interceptor'; @Controller('test') @UseInterceptors(TimeoutInterceptor) export class TestController { @Get('fast') fastResponse(): Observable<string> { return of('Fast response').pipe(delay(1000)); // responds in 1 second } @Get('slow') slowResponse(): Observable<string> { return of('Slow response').pipe(delay(6000)); // responds in 6 seconds } }
OutputSuccess
Important Notes
Set the timeout value based on your app's needs and expected response times.
Use this interceptor globally or on specific controllers/routes.
Remember to import and provide the interceptor properly in your module.
Summary
A timeout interceptor stops requests that take too long.
It uses RxJS timeout and catches errors to send a timeout response.
Use it to keep your app responsive and avoid waiting forever.