Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 39 ยท Schemas and Validation

Shared Schemas and $ref

Stop repeating yourself: register shared JSON Schemas with addSchema, reference them with $ref, build create/update variants and scope schemas to plugins.

The first time you write a user schema, it lives inside one route. The second time, you copy it. By the fifth route the copies have drifted apart: one says name is required, another allows 500 characters, a third forgot the email format. Fastify solves this with shared schemas: you give a schema an $id, register it with app.addSchema(), and refer to it from any route with $ref.

This lesson covers registering and referencing schemas, building "create", "update" and "list" variants from one definition, and how shared schemas follow the encapsulation rules you will meet in the plugins chapter.

Registering a schema

A shared schema is a normal schema with a required $id:

JavaScript
app.addSchema({
  $id: 'user',
  type: 'object',
  required: ['name', 'email'],
  properties: {
    id: { type: 'integer' },
    name: { type: 'string', minLength: 1, maxLength: 80 },
    email: { type: 'string', format: 'email' },
  },
});

Any route can then use it by reference:

JavaScript
app.post('/users', { schema: { body: { $ref: 'user#' } } }, handler);

The # at the end means "the whole schema". You can also point to a part with a JSON Pointer: { $ref: 'user#/properties/email' } reuses only the email definition. The format is <id>#<pointer>.

Node.js addSchema and $ref

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.

One definition now drives two routes. If you later change the maximum length of name, every route that references it changes with it.

Building variants: create, update, response

A single "user" rarely fits every endpoint. A create request must not include id; an update allows any field but requires at least one; a response includes id and hides secrets. Do not copy the schema three times. Build variants from the shared pieces, in plain JavaScript:

JavaScript
const userFields = {
  name: { type: 'string', minLength: 1, maxLength: 80 },
  email: { type: 'string', format: 'email' },
  role: { type: 'string', enum: ['member', 'admin'] },
};

app.addSchema({ $id: 'userCreate', type: 'object', required: ['name', 'email'], additionalProperties: false, properties: { ...userFields, role: { ...userFields.role, default: 'member' } } });
app.addSchema({ $id: 'userUpdate', type: 'object', minProperties: 1, additionalProperties: false, properties: userFields });
app.addSchema({ $id: 'userOut',    type: 'object', properties: { id: { type: 'integer' }, ...userFields } });

Because schemas are plain objects, ordinary JavaScript (...spread, Object.fromEntries, small helper functions) is the best tool for composition. The two or three lines that differ stay visible and everything else is shared.

Node.js Create, update and output variants from one set of fields

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.

Notice three things. The unknown key isAdmin was stripped (because of additionalProperties: false). The default role: 'member' was filled in on create (only there: a default in the update schema would silently reset the role on every PATCH). And the response schema userOut removed passwordHash: a response schema is a whitelist, so fields you did not declare are never sent. (The serialization chapter explains this in detail.)

Where $ref can point

$ref value Meaning
'user#' The whole schema registered with $id: 'user'
'user#/properties/email' One property of that schema
'user#/definitions/address' A named piece you put under definitions (or $defs)
'#/definitions/address' A piece defined in the same schema

A common pattern is a common schema that holds small reusable pieces:

JavaScript
app.addSchema({
  $id: 'common',
  definitions: {
    id: { type: 'integer', minimum: 1 },
    page: { type: 'integer', minimum: 1, default: 1 },
    pageSize: { type: 'integer', minimum: 1, maximum: 100, default: 20 },
  },
});

// elsewhere
properties: { page: { $ref: 'common#/definitions/page' }, size: { $ref: 'common#/definitions/pageSize' } }

Scope: shared schemas follow encapsulation

addSchema is a scoped operation, like decorators and hooks. A schema added on the root instance is visible everywhere. A schema added inside a plugin is visible in that plugin and its children only. That has two consequences:

  1. Register truly shared schemas (common, user, error) on the root app, or in a plugin wrapped with fastify-plugin (see the plugin chapter).
  2. Two sibling plugins may each define a schema with the same $id without clashing, but adding the same $id twice in one scope throws an error at startup. Use the $id as a name, not as a place to improvise.

You can read a registered schema back with app.getSchema('user'), and app.getSchemas() returns all schemas visible in the current scope. Both are useful in tests and when you generate documentation.

Common mistakes

  • Referencing a schema that is registered later or in another scope. The error appears at startup ("can't resolve reference"), not at request time. Register shared schemas before the routes that use them.
  • Forgetting the #. { $ref: 'user' } does not resolve; write { $ref: 'user#' }.
  • Mutating a registered schema object. Build variants with spread syntax into new objects. Editing the original after registering it leads to confusing behavior.
  • One mega-schema for everything. A create body, an update body and a response need different rules; share the field definitions, not the whole object.
  • Reusing a response schema as a request schema without checking required. A response may include id; a create request must not.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which field is required on a schema passed to app.addSchema()?

    Fastify stores shared schemas by their $id, so addSchema throws when it is missing.
  2. 2. How do you reference only the email property of a schema registered as 'user'?

    A $ref has the form <id>#<JSON pointer>; the pointer /properties/email selects one property.
  3. 3. A response schema declares id, name and email. The handler sends an object that also contains passwordHash. What does the client receive?

    Response schemas act as a whitelist: undeclared properties are dropped during serialization.
  4. 4. What is the best way to build 'create' and 'update' schemas from the same fields?

    Schemas are plain objects, so ordinary composition keeps one source of truth while the differences (required, additionalProperties) stay visible.

Summary

  • app.addSchema({ $id, ... }) registers a reusable schema; { $ref: 'id#' } or 'id#/pointer' uses it.
  • Build create, update and output variants by composing shared property objects in JavaScript.
  • Keep tiny reusable pieces (id, page, pageSize) in a common schema under definitions.
  • Shared schemas are scoped like decorators: register global ones on the root or in a fastify-plugin plugin.
  • Unresolved references fail at startup, which is when you want to find out.

Next: Validation Errors and Formatting