typescript
60 lines · 7 steps
Wrapping responses in a NestJS interceptor
A NestJS interceptor that wraps every controller response in a consistent envelope with request metadata, while allowing opt-out per route.
Explained by
highlit
1import {
2 CallHandler,
3 ExecutionContext,
4 Injectable,
5 NestInterceptor,
6} from '@nestjs/common';
7import { Reflector } from '@nestjs/core';
8import { Request } from 'express';
9import { Observable } from 'rxjs';
10import { map } from 'rxjs/operators';
11import { randomUUID } from 'crypto';
12
13export interface ResponseEnvelope<T> {
14 success: true;
15 data: T;
16 meta: {
17 requestId: string;
18 timestamp: string;
19 path: string;
20 };
21}
22
23@Injectable()
24export class ResponseEnvelopeInterceptor<T>
25 implements NestInterceptor<T, ResponseEnvelope<T> | T>
26{
27 constructor(private readonly reflector: Reflector) {}
28
29 intercept(
30 context: ExecutionContext,
31 next: CallHandler<T>,
32 ): Observable<ResponseEnvelope<T> | T> {
33 const skip = this.reflector.getAllAndOverride<boolean>('skipEnvelope', [
34 context.getHandler(),
35 context.getClass(),
36 ]);
37
38 const request = context.switchToHttp().getRequest<Request>();
39 const requestId =
40 (request.headers['x-request-id'] as string) ?? randomUUID();
41
42 return next.handle().pipe(
43 map((data) => {
44 if (skip) {
45 return data;
46 }
47
48 return {
49 success: true,
50 data,
51 meta: {
52 requestId,
53 timestamp: new Date().toISOString(),
54 path: request.originalUrl,
55 },
56 } satisfies ResponseEnvelope<T>;
57 }),
58 );
59 }
60}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Interceptors let you transform every outgoing response in one place instead of repeating shape logic in each controller.
- 2The Reflector reads custom metadata so individual routes can opt out of cross-cutting behavior.
- 3Operating on the RxJS stream from next.handle() means the transform runs after the handler resolves its value.
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
typescript
import { Injectable, Scope, Inject, NotFoundException } from '@nestjs/common'; import { REQUEST } from '@nestjs/core'; import { Request } from 'express'; import { DataSource } from 'typeorm';
Per-tenant database connections in NestJS
multi-tenancy
connection-pooling
dependency-injection
Advanced
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/wrapping-responses-in-a-nestjs-interceptor-explained-typescript-1d5c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.