Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 39 ยท Serialization and Performance

Response Serialization and Schemas

Understand Fastify response serialization: response schemas, per-status schemas, stripping private fields, type coercion, required properties and custom serializers.

Every JSON response has to be turned into text. In most Node frameworks that is a single call to JSON.stringify, which inspects each value at runtime to figure out what it is. Fastify offers a better way: describe the response with a schema, and Fastify compiles a specialized serializer for exactly that shape, using the fast-json-stringify library. The serializer knows in advance that id is an integer and name is a string, so it can write the output with far less work.

Speed is only half of the story. A response schema is also a safety net: only the properties listed in the schema reach the client. If a developer accidentally returns a whole database row, including passwordHash, the schema quietly removes it. This lesson shows both benefits.

Real Fastify and fast-json-stringify are not installed on this site. The examples use the stand-in from The Fastify Request Lifecycle, whose small serializer copies the behaviors discussed here: keep only listed properties, coerce types, and fail when a required property is missing. The real library supports much more JSON Schema, and compiles to JavaScript source instead of walking the schema at runtime.

The response schema

You attach it under schema.response, keyed by status code:

JavaScript
// real Fastify
app.get('/users/:id', {
  schema: {
    response: {
      200: {
        type: 'object',
        required: ['id', 'name'],
        properties: {
          id: { type: 'integer' },
          name: { type: 'string' },
          email: { type: 'string' },
        },
      },
    },
  },
}, async (request) => db.findUser(request.params.id));

Whatever the handler returns, the JSON that leaves the server contains at most id, name and email, in the order of the schema. Extra properties are dropped; this is the single most useful security feature in the serializer.

Node.js Private fields never leave the server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first route leaks the hash. The second returns only three fields, and id arrived as the string "7" in the row but leaves as the number 7, because the schema says integer (serializers coerce where they can). The third shows that items applies the schema to every element.

One schema per status code

A route has more than one possible outcome. List each with its own shape, and use 2xx, 4xx or default for ranges:

JavaScript
response: {
  200: userSchema,
  404: { type: 'object', properties: { message: { type: 'string' } } },
  '4xx': errorSchema,
}

Fastify picks the most specific key: exact code first, then the 2xx/4xx range, then default. Declaring error shapes also documents them for tools that generate OpenAPI files from schemas.

When the data does not fit

A serializer cannot invent data. If a property is marked required and the object lacks it, real fast-json-stringify throws an error such as "email" is required!, and Fastify answers with a 500. That is a good thing during development: your response drifted from your contract and you find out in the first test.

Node.js Required properties and status-specific schemas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the three results: kb-1 has price: "19.90" turned into the number 19.9, inStock: 1 into true, and supplier removed. missing returns only the message (the internal note is stripped by the 404 schema). broken fails with 500 because price is required.

Coercion helps, but do not rely on it for correctness. A price stored as a string is a data-model bug. Fix it at the source, and let the schema be the last line of defense.

Reusing schemas with $ref

Real applications define a schema once and refer to it everywhere. Register it with app.addSchema({ $id: 'user', ... }) and point to it with { $ref: 'user#' } in any route. A change in one place updates every request and response that uses it. Shared schemas are encapsulated like everything else: a schema added in a plugin is visible to that plugin and its children.

JavaScript
// real Fastify
app.addSchema({ $id: 'user', type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } } });

app.get('/users', { schema: { response: { 200: { type: 'array', items: { $ref: 'user#' } } } } }, listUsers);

Custom serializers

Sometimes JSON is not the output format, or you need a special serializer for one route. Two tools exist:

  • reply.serializer(fn) sets a serializer for one reply (for example, to produce CSV from rows).
  • app.setReplySerializer(fn) replaces the default for the whole instance. setSerializerCompiler customizes how schemas become serializers (for example, to use another library).
JavaScript
// real Fastify
app.get('/report.csv', async (request, reply) => {
  const rows = await loadRows();
  return reply
    .type('text/csv')
    .serializer((payload) => payload.map((r) => r.join(',')).join('\n'))
    .send(rows);
});

If a handler returns a string, Fastify sends it as text (text/plain), not JSON. Return an object when you want JSON, or set reply.type('application/json') and send a pre-serialized string when you have already produced the JSON yourself (for example from a cache).

Guidelines

  1. Add a 200 response schema to every route that returns data. It is cheap insurance.
  2. List only what clients need. Treat the schema as the public contract.
  3. Mark properties required only when they always exist, otherwise a missing field becomes a 500.
  4. Use additionalProperties: false when you also want validation to reject unknown fields on input schemas.
  5. Keep nested schemas shallow where you can; huge deeply nested schemas slow compilation at startup (not requests).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to properties that are NOT listed in the response schema?

    The compiled serializer only writes properties it knows. Extras, such as a password hash, are dropped.
  2. 2. A response schema marks price as required, but the handler returns an object without it. What is the outcome?

    The serializer throws because the data does not match the contract, so the client gets a 500. This is caught early in tests.
  3. 3. How do you give different shapes to a 200 and a 404 response?

    schema.response is keyed by status code (and ranges like 2xx, 4xx or default).
  4. 4. What does Fastify do if a handler returns a plain string?

    Strings are already final bytes, so they are sent as text. Return an object to get JSON.

Summary

  • A response schema compiles to a fast, specialized serializer and acts as a filter for what clients may see.
  • Properties not in the schema are removed; types are coerced where possible; missing required properties cause a 500.
  • Declare shapes per status code, with 2xx, 4xx and default ranges for convenience.
  • Share schemas with addSchema and $ref; use reply.serializer or a serializer compiler for custom formats.
  • Strings are sent as text, so return objects when you want JSON.

Next: Content-Type Parsers, Streams and Custom Replies