Skip to content

Serialization

intermediate2 min read
  • NestJS
  • Node.js

Converting in-memory objects into a transferable format such as JSON, and controlling exactly which fields are exposed so internal data never leaks.

What you'll understand

  • What serialization and deserialization are
  • Why JSON is the usual format for APIs
  • How to control which fields appear in a serialized response

Explanation

Serialization is the process of turning an in-memory object into a format that can be stored or sent over the network, and deserialization is the reverse. For web APIs that format is almost always JSON, because it is text-based, language-neutral, and maps naturally onto the objects both servers and clients use. Every JSON response your API sends is the result of serializing an object.

The important part is not that serialization happens, it is that you control what it produces. An internal object often contains fields a client should never see: a password hash, an internal flag, a soft-delete marker. Serialization is the boundary where you decide what to expose. If you serialize a raw entity blindly, those fields go out with it.

Frameworks give you tools to shape this. In NestJS, class-transformer lets you mark a field to be excluded so it is stripped from every response, and to transform values on the way out. The principle is the same whatever the tool: treat the serialized output as a deliberate representation of the resource (closely related to response DTOs), not an automatic dump of whatever object you happened to have.

Examples

This TypeScript example excludes a sensitive field so it is never serialized into a response:

import { Exclude } from 'class-transformer';

export class UserEntity {
  id!: number;
  email!: string;

  @Exclude()
  passwordHash!: string;
}

With serialization enabled, returning the entity yields JSON without the excluded field:

// GET /users/1 responds with:
{ "id": 1, "email": "ada@example.com" }

Common mistakes

  • Serializing raw entities and leaking sensitive fields like password hashes.
  • Building JSON strings by hand instead of serializing structured objects.
  • Assuming every field should be exposed just because it exists on the object.
  • Forgetting to deserialize and validate incoming data before trusting it.

Best practices

  • Treat the serialized response as a deliberate representation you control.
  • Exclude internal and sensitive fields from serialization explicitly.
  • Prefer framework serialization over hand-built JSON strings.
  • Keep response shapes consistent by pairing serialization with response DTOs (see Related Topics).

Further reading

Related topics

Serialization — Padlor · Padlor