Response Schemas

Faster JSON & Hidden Internals

Response Schemas

Response schemas drive fast-json-stringify and strip undeclared fields, giving you both a speed boost and a safety net against leaking internal data.

4 min read Level 3/5 #fastify#schemas#serialization
What you'll learn
  • Declare per-status response schemas
  • Use additionalProperties false to strip extra fields
  • Understand the serialization speedup

Response schemas are easy to ignore — but they pay back disproportionately. Two reasons: they make serialization roughly 3x faster and they keep sensitive fields out of the wire payload.

Status-Keyed Responses

const userSchema = {
  type: 'object',
  properties: {
    id: { type: 'integer' },
    email: { type: 'string', format: 'email' },
    createdAt: { type: 'string', format: 'date-time' },
  },
  required: ['id', 'email'],
} as const;

app.get('/me', {
  schema: {
    response: {
      200: userSchema,
      401: {
        type: 'object',
        properties: { message: { type: 'string' } },
      },
    },
  },
  handler: async (req) => {
    return db.users.findCurrent(req); // returns { id, email, passwordHash, ... }
  },
});

Even though the row carries passwordHash, the serializer only writes id, email, and createdAt to the response. No more manually picking columns or remembering to scrub fields.

Why It’s Faster

Fastify uses fast-json-stringify, which compiles the schema into a hand-rolled JS function at boot. There’s no per-call schema walk and no type checks — it knows the layout in advance. Hot endpoints see 2-3x throughput improvements.

Match Multiple Status Codes

Use the 2xx, 3xx, etc. wildcards when the shape repeats:

response: {
  '2xx': userSchema,
  '4xx': { type: 'object', properties: { message: { type: 'string' } } },
}

If you return a status not covered by any key, Fastify falls back to JSON.stringify.

TypeBox — Schemas as TypeScript →