Nest.js Tutorial

Serializing the response with interceptors

Marcin Wanago
JavaScriptNestJSTypeScript

Sometimes we need to perform additional operations on the outcoming data. We might not want to expose specific properties or modify the response in some other way. In this article, we look into various solutions NestJS provides us with to change the data we send in the response.

You can find the code from this series in this repository.

Serialization

The first thing to look into is the serialization. It is a process of transforming the response data before returning it to the user.

In the previous parts of this series, we’ve removed the password in the various parts of our API. A better approach would be using the class-transformer.

users/user.entity.ts
1import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
2import { Exclude } from 'class-transformer';
3 
4@Entity()
5class User {
6  @PrimaryGeneratedColumn()
7  public id?: number;
8 
9  @Column({ unique: true })
10  public email: string;
11 
12  @Column()
13  public name: string;
14 
15  @Column()
16  @Exclude()
17  public password: string;
18}
19 
20export default User;

NestJS comes equipped with  ClassSerializerInterceptor that uses class-transformer under the hood. To apply the above transformation, we need to use it in our controller:

1@Controller('authentication')
2@UseInterceptors(ClassSerializerInterceptor)
3class AuthenticationController

If we find ourselves adding ClassSerializerInterceptor to a lot of controllers, we can configure it globally instead.

main.ts
1import { NestFactory, Reflector } from '@nestjs/core';
2import { AppModule } from './app.module';
3import * as cookieParser from 'cookie-parser';
4import { ClassSerializerInterceptor, ValidationPipe } from '@nestjs/common';
5 
6async function bootstrap() {
7  const app = await NestFactory.create(AppModule);
8  app.useGlobalPipes(new ValidationPipe());
9  app.useGlobalInterceptors(new ClassSerializerInterceptor(
10    app.get(Reflector))
11  );
12  app.use(cookieParser());
13  await app.listen(3000);
14}
15bootstrap();
The  ClassSerializerInterceptor needs the Reflector when initializing.

By default, all properties of our entities are exposed. We can change this strategy by providing additional options to the class-transformer. To do so, we need to use the  @SerializeOptions() decorator.

1@Controller('authentication')
2@SerializeOptions({
3  strategy: 'excludeAll'
4})
5export class AuthenticationController
users/user.entity.ts
1import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
2import { Expose } from 'class-transformer';
3 
4@Entity()
5class User {
6  @PrimaryGeneratedColumn()
7  public id?: number;
8 
9  @Column({ unique: true })
10  @Expose()
11  public email: string;
12 
13  @Column()
14  @Expose()
15  public name: string;
16 
17  @Column()
18  public password: string;
19}
20 
21export default User;

The  @SerializeOptions() decorator has more options that you might find useful. It matches the options that you can provide for the  classToPlain method in the class-transformer.

The class-transformer library has quite a few useful features. Another noteworthy one is the ability to transform values. To demonstrate it, let’s create a nullable column:

1@Entity()
2class Post {
3  // ...
4 
5  @Column({ nullable: true })
6  public category?: string;
7}

Since the  category is a nullable column, it is optional, its value is null until we set it. This means sending null values in the response:

The above behavior might be considered undesirable and the most straightforward way to fix it is to use the  @Transform decorator. If the value equals null, we don’t want to send in the response.

1@Column({ nullable: true })
2@Transform(value => {
3  if (value !== null) {
4    return value;
5  }
6})
7public category?: string;

Issues with using the @Res() decorator

In the previous part of this series, we’ve used the  @Res() decorator to access the Express Response object. Thanks to that, we were able to attach cookies to the response.

1@HttpCode(200)
2@UseGuards(LocalAuthenticationGuard)
3@Post('log-in')
4async logIn(@Req() request: RequestWithUser, @Res() response: Response) {
5  const {user} = request;
6  const cookie = this.authenticationService.getCookieWithJwtToken(user.id);
7  response.setHeader('Set-Cookie', cookie);
8  user.password = undefined;
9  return response.send(user);
10}

Using the  @Res() decorator strips us from some advantages of using NestJS. Unfortunately, it interferes with the  ClassSerializerInterceptor. To prevent that, we can follow some advice from the creator of NestJS. If we use the  request.res object instead of the  @Res() decorator, we don’t put NestJS into the express-specific mode.

1@HttpCode(200)
2@UseGuards(LocalAuthenticationGuard)
3@Post('log-in')
4async logIn(@Req() request: RequestWithUser) {
5  const {user} = request;
6  const cookie = this.authenticationService.getCookieWithJwtToken(user.id);
7  request.res.setHeader('Set-Cookie', cookie);
8  return user;
9}

The above is a neat little trick that we use to take advantage of the mechanisms built into NestJS while accessing the Response object directly.

Custom interceptors

Above, we use the  @Transform decorator to skip a single property if it equals null. Doing so for every nullable property does not seem like a clean approach.

Fortunately, aside from using the  ClassSerializerInterceptor, we can create our own interceptors. Interceptors can serve various purposes, and one of them is manipulating the request/response stream.

utils/excludeNull.interceptor.ts
1import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
2import { Observable } from 'rxjs';
3import { map } from 'rxjs/operators';
4import recursivelyStripNullValues from './recursivelyStripNullValues';
5 
6@Injectable()
7export class ExcludeNullInterceptor implements NestInterceptor {
8  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
9    return next
10      .handle()
11      .pipe(map(value => recursivelyStripNullValues(value)));
12  }
13}

Each interceptor needs to implement the  NestInterceptor and, therefore, the  intercept method. It takes two arguments:

  • ExecutionContext it provides information about the current context,
  • CallHandler it contains the  handle method that invokes the route handler and returns an RxJS Observable

The  intercept method wraps the request/response stream, and we can add logic both before and after the execution of the route handler. In the above code, we invoke the route handle and modify the response.

Since there are quite a few places in the NestJS framework that make use of RxJS, the official TypeScript starter already contains it.

utils/recursivelyStripNullValues.ts
1function recursivelyStripNullValues(value: unknown): unknown {
2  if (Array.isArray(value)) {
3    return value.map(recursivelyStripNullValues);
4  }
5  if (value !== null && typeof value === 'object') {
6    return Object.fromEntries(
7      Object.entries(value).map(([key, value]) => [key, recursivelyStripNullValues(value)])
8    );
9  }
10  if (value !== null) {
11    return value;
12  }
13}

In the above function, we recursively travel the data structure and preserve values only if they differ from null. It works both for arrays and plain objects.

If you want to know more about recursion in JavaScript, check out Using recursion to traverse data structures. Execution context and the call stack Also, every recursive function can be turned into an iterative one

Summary

In this article, we’ve looked into how we can modify the response that we send back to our users. While the most straightforward way to do so is to serialize the response with  ClassSerializerInterceptor, we can also create our own interceptor. We’ve also looked into how we can bypass the issue of using the @Res() decorator.