Skip to content

Serialization

Olli R edited this page Aug 27, 2025 · 4 revisions

The app has two edges where it interacts with the outside world: the incoming HTTP requests, and data coming from remote sources (databases and REST APIs). On top of serializing that into JSON, we can serialize it into JS class instances. A good internal model of the outside world helps our internal logic to do stuff.

Serializing into classes helps with:

  • Validating input data from incoming HTTP requests
  • Adding default values to data either from the incoming HTTP requests or remote sources
  • Excluding properties from HTTP responses

Technically

For the incoming HTTP requests, Nest's ValidationPipe transforms the body automatically to the DTO defined in the controller.

For remote data, database responses must be manually serialized. For REST API responses, our REST client has the option to serialize the response. Note that for large array responses this can create performance problems. Serialization isn't a must do - if you don't need to have any default values for the response, there's no need serialize. If you don't need the data to be serialized in the service layer, but some properties need to be excluded for the http response in the controller level, it's better to leave the serialization for the query-params.interceptor, which can do the serialization for the paged result only, which should be quite performant.

Nest's implementation for serialization doesn't work very well when used with the swagger CLI plugin. For this reason, we have a custom solution for serialization (serializeInto from src/serialization/serialization.utils.ts). It should be used when serializing manually. The automatically applied serialization uses it.

Clone this wiki locally