0
0
NestJSframework~30 mins

Timeout interceptor in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Timeout Interceptor in NestJS
📖 Scenario: You are building a NestJS backend API that needs to cancel requests that take too long. This helps keep your server responsive and avoids waiting forever for slow operations.
🎯 Goal: Create a TimeoutInterceptor that cancels any request taking longer than a set time limit.
📋 What You'll Learn
Create a class called TimeoutInterceptor that implements NestInterceptor
Add a constructor that accepts a timeout value in milliseconds
Use rxjs operators to apply the timeout to the request handling
Throw a RequestTimeoutException if the timeout is exceeded
💡 Why This Matters
🌍 Real World
Timeout interceptors help keep backend APIs responsive by cancelling slow requests, improving user experience and resource usage.
💼 Career
Understanding interceptors and RxJS operators is essential for backend developers working with NestJS to build robust and maintainable APIs.
Progress0 / 4 steps
1
Create the TimeoutInterceptor class
Create a class called TimeoutInterceptor that implements NestInterceptor from @nestjs/common. Import Injectable and decorate the class with it.
NestJS
Need a hint?

Remember to import Injectable and NestInterceptor from @nestjs/common and decorate your class with @Injectable().

2
Add a constructor with timeout value
Add a constructor to TimeoutInterceptor that accepts a single parameter called timeout of type number. Store it as a private readonly property.
NestJS
Need a hint?

Use constructor(private readonly timeout: number) {} to store the timeout value.

3
Implement the intercept method with timeout logic
Implement the intercept method with parameters context: ExecutionContext and next: CallHandler. Import Observable from rxjs and timeout operator from rxjs/operators. Return next.handle().pipe(timeout(this.timeout)).
NestJS
Need a hint?

Use next.handle().pipe(timeout(this.timeout)) to apply the timeout.

4
Throw RequestTimeoutException on timeout
Import RequestTimeoutException from @nestjs/common. Modify the intercept method to catch timeout errors and throw RequestTimeoutException instead. Use catchError from rxjs/operators and throwError from rxjs.
NestJS
Need a hint?

Use catchError to check if the error is a timeout and throw RequestTimeoutException.