Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 39 ยท Schemas and Validation

JSON Schema Basics in Fastify

Learn how Fastify uses JSON Schema to validate requests: types, required fields, constraints, defaults, coercion and what a failed validation looks like.

Until now your handlers trusted whatever arrived. In a real service that is a bug waiting to happen: a missing field becomes undefined deep inside your code, a string where you expected a number slips into a database query, and a client that sends 10 MB of nonsense gets a 500 instead of a clear answer. Fastify's answer is to describe the data you accept with a JSON Schema and let the framework check it before your handler runs.

This lesson teaches the schema vocabulary you will use every day, where schemas plug into a route, and what Fastify does with the result. The next lessons build on it: validating every part of a request, sharing schemas and shaping the error messages.

Fastify itself is not installed on this site, so the runnable examples use a small stand-in (a few dozen lines at the top of each example) that implements register, hooks, decorators and JSON Schema validation with the same messages Fastify prints. Everything below the line end of the stand-in is exactly what you would write with the real fastify package (version 5). The real validator is Ajv; the stand-in covers the keywords used in these lessons.

What is JSON Schema?

JSON Schema is a standard way to describe JSON data as JSON. A schema is an object that says "this value must be an object with a string name, an integer age of at least 0, and an optional email":

JavaScript
const userSchema = {
  type: 'object',
  properties: {
    name: { type: 'string', minLength: 1 },
    age: { type: 'integer', minimum: 0 },
    email: { type: 'string', format: 'email' },
  },
  required: ['name', 'age'],
};

Read it from the top. type: 'object' says the value is an object. properties lists the keys you know about and a schema for each one (schemas nest). required lists the keys that must be present. Keys that are in properties but not in required are optional.

Because a schema is plain data, Fastify can compile it once at startup into a fast validation function, and reuse it for every request. That is part of why validation costs very little.

The vocabulary you will use most

Keyword Applies to Meaning
type any string, number, integer, boolean, object, array, null
properties object A schema for each known key
required object Array of keys that must be present
additionalProperties object false rejects (or strips) unknown keys
minLength, maxLength string Length limits
pattern string A regular expression the value must match
format string email, uuid, date, date-time, uri, ...
minimum, maximum number Inclusive limits
enum any The value must be one of a fixed list
items array A schema for every element
minItems, maxItems array Length limits
default any Value to use when the key is missing

integer is a number without a fractional part, so 3 passes and 3.5 does not. format checks are provided by the ajv-formats package that Fastify's default validator includes.

Where schemas go

A route accepts a schema option with up to five parts. Each one describes a different piece of the request or response:

Key What it validates
body The parsed request body (POST, PUT, PATCH)
querystring (or query) The ?a=1&b=2 part of the URL
params Path parameters such as :id
headers Request headers (names are lowercase)
response What you send back, per status code (covered in the serialization chapter)
JavaScript
app.post('/users', {
  schema: {
    body: userSchema,
  },
}, async (request, reply) => {
  // If we get here, request.body already matches userSchema.
  return reply.code(201).send(request.body);
});

Fastify 5 expects complete JSON Schemas. Older versions accepted a shorthand such as querystring: { limit: { type: 'integer' } }; version 5 requires { type: 'object', properties: { limit: { type: 'integer' } } }. If you copy code from an old article and see a validation setup error at startup, this is the usual reason.

Your first validated route

Run this example. It defines the schema above, sends one valid and three invalid requests, and prints what the client would receive.

Node.js A validated POST route

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 request passes and your handler runs. The other three never reach it: Fastify answers 400 Bad Request with a body that names the failing part (body, then the path inside it, then the problem). The code field, FST_ERR_VALIDATION, is stable, so clients and your own error handler can recognize validation failures without parsing the message.

flowchart LR
  A["Request arrives"] --> B["onRequest hooks"]
  B --> C["Parse body"]
  C --> D["preValidation hooks"]
  D --> E{"Schema valid?"}
  E -- "yes" --> F["preHandler hooks"]
  F --> G["Your handler"]
  E -- "no" --> H["400 FST_ERR_VALIDATION"]

Validation sits between parsing and preHandler: the handler never sees invalid data.

Fastify cleans your data as it validates

Fastify configures Ajv with three options that surprise newcomers, so learn them now:

  1. coerceTypes: values are converted to the declared type when that is safe. "42" becomes 42 for an integer, "true" becomes true for a boolean, and a single query value becomes an array for an array schema. This is what makes query strings (which are always text) usable.
  2. useDefaults: a default in the schema is written into the data when the key is missing.
  3. removeAdditional: with additionalProperties: false, unknown keys are silently removed rather than reported as errors.

Because Fastify changes request.body, request.query and request.params in place, your handler reads the cleaned values. Try it:

Node.js Coercion, defaults and stripped keys

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.

Look at each line of output. The first request gets limit: 10 and exact: false from the defaults. The second shows "25" turned into 25, "true" into true and tag wrapped into an array. The third fails because 500 is above the maximum. The fourth is missing the required q. In the last one, "41" became 41 and the unknown admin key disappeared, so a client cannot sneak extra fields into your handler this way.

removeAdditional is a safety net, not an error report. If you would rather reject unknown keys, set additionalProperties: false and also configure Ajv with removeAdditional: false (an option shown in a later lesson), or check keys yourself in a preValidation hook.

Writing good schemas

A few habits keep schemas readable and your API pleasant to use:

  • Constrain everything that comes from outside. A string with no maxLength lets a client send a megabyte for a "name". Pick realistic limits.
  • Prefer enum over free text when the set of values is known (status: { enum: ['draft', 'published'] }).
  • Mark what is required, not what is optional. Required lists are short and easy to scan.
  • Give defaults in the schema instead of in the handler, so documentation and behavior stay in one place.
  • Keep one schema per concept and reuse it (the $ref lesson shows how).

Common mistakes

  • Forgetting type: 'object' at the top of a body, querystring, params or headers schema. Without it Fastify 5 cannot tell what you meant.
  • Using uppercase header names in a headers schema. Node lowercases header names, so write authorization, not Authorization.
  • Trusting coercion too much. "5" to 5 is helpful, but coercion also turns false into 0, a number into a string and a lone value into a one-element array. Add minimum, minLength or enum where such values make no sense, and test the edge cases.
  • Validating in the handler too. If the schema already guarantees a shape, extra if (!request.body.name) checks are noise. Business rules (is this email already taken?) still belong in the handler.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does Fastify run schema validation, relative to your route handler?

    Validation runs after body parsing and preValidation hooks, and before preHandler hooks and the handler.
  2. 2. A querystring schema declares limit as an integer. The URL has ?limit=25. What does the handler see in request.query.limit?

    Fastify's Ajv configuration uses coerceTypes, so numeric strings become numbers for integer and number schemas.
  3. 3. What happens to an unknown key when the schema sets additionalProperties to false (with Fastify's defaults)?

    Fastify enables removeAdditional, so unknown keys are stripped silently when additionalProperties is false.
  4. 4. Which HTTP status and code does a failed validation produce by default?

    Validation failures are client errors: 400 Bad Request with the code FST_ERR_VALIDATION.

Summary

  • A JSON Schema describes the data you accept; Fastify compiles it once and checks every request before the handler runs.
  • Use schema.body, querystring, params and headers on a route; Fastify 5 wants full schemas with type: 'object'.
  • Key keywords: type, properties, required, minLength, maximum, enum, items, default, format.
  • Fastify coerces types, applies defaults and strips unknown keys when additionalProperties is false, so handlers see clean data.
  • Failures return 400 with code: "FST_ERR_VALIDATION" and a message that names the failing part.

Next: Validating Request Parts