Did you try this ?
- NestJs: https://docs.nestjs.com/interceptors#more-operators
- For express: https://github.com/expressjs/timeout
Example:
```javascript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, RequestTimeoutException } from '@nestjs/common';
import { Observable, throwError, TimeoutError } from 'rxjs';
import { catchError, timeout } from 'rxjs/operators';
@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
timeout(5000),
catchError(err => {
if (err instanceof TimeoutError) {
return throwError(() => new RequestTimeoutException());
}
return throwError(() => err);
}),
);
};
};
```
NestJS has a feature called Interceptors. Interceptors can be used for the purpose of forcing timeouts, they demonstrate it here, [TimeoutInterceptor][1].
Suppose you have got your Interceptor in a file called `timeout.interceptor.ts`:
```
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, RequestTimeoutException } from '@nestjs/common';
import { Observable, throwError, TimeoutError } from 'rxjs';
import { catchError, timeout } from 'rxjs/operators';
@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
timeout(5000),
catchError(err => {
if (err instanceof TimeoutError) {
return throwError(new RequestTimeoutException());
}
return throwError(err);
}),
);
};
};
```
After this, you have to register it, which can be done in several ways. The global registration way is shown below:
```
const app = await NestFactory.create(AppModule);
app.useGlobalInterceptors(new TimeoutInterceptor());
```
[1]: https://docs.nestjs.com/interceptors#more-operators