Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 39 ยท Schemas and Validation

Validating Request Parts

Validate every part of a Fastify request: body, params, querystring and headers. Learn the error format, attachValidation and handling errors in one place.

A request has four places where client-controlled data hides: the body, the path parameters, the query string and the headers. A bug in any of them can hurt you, so Fastify lets one route validate all four at once. This lesson shows how each part is declared, what order Fastify checks them in, and how to react to failures, either with the default 400 or with your own logic.

If JSON Schema keywords are new to you, read JSON Schema Basics first.

One route, four schemas

JavaScript
app.put('/projects/:projectId/tasks', {
  schema: {
    params:      { type: 'object', properties: { projectId: { type: 'integer', minimum: 1 } }, required: ['projectId'] },
    querystring: { type: 'object', properties: { notify: { type: 'boolean', default: false } } },
    headers:     { type: 'object', properties: { 'x-api-version': { type: 'string', enum: ['1', '2'] } }, required: ['x-api-version'] },
    body:        { type: 'object', properties: { title: { type: 'string', minLength: 3 } }, required: ['title'] },
  },
}, handler);

Things to remember about each part:

  • params: path values are always strings in the URL; with type: 'integer' Fastify converts them. Declare them in required so a route like /projects/:projectId cannot be reached with garbage.
  • querystring: every value starts as text. Declare booleans, numbers and arrays and let coercion do the work. A repeated key (?tag=a&tag=b) becomes an array when the schema says type: 'array'.
  • headers: header names are lowercase in Node, so the schema uses 'x-api-version', never 'X-Api-Version'. Headers sent by browsers and proxies (such as host and user-agent) are present too, so do not use additionalProperties: false on a headers schema.
  • body: validated after the content-type parser has produced request.body. A GET has no body, so a body schema belongs on POST, PUT, PATCH and DELETE routes.

Fastify checks the parts in a fixed order: headers, params, querystring, body. The first failure stops the request, and the message starts with the part that failed.

Node.js Validating all four parts

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 how little code the handler needs. Every value is already the right type: projectId is the number 7, notify is the boolean true. The failing requests tell the client exactly where the problem is (params/projectId must be integer, headers must have required property 'x-api-version'), which is far better than a vague 500.

Validating arrays and nested objects

Schemas nest. A body that holds a list of line items, each with its own rules, looks like this:

JavaScript
const orderBody = {
  type: 'object',
  required: ['customer', 'items'],
  properties: {
    customer: {
      type: 'object',
      required: ['email'],
      properties: { email: { type: 'string', format: 'email' }, name: { type: 'string' } },
    },
    items: {
      type: 'array',
      minItems: 1,
      maxItems: 100,
      items: {
        type: 'object',
        required: ['sku', 'qty'],
        properties: { sku: { type: 'string', pattern: '^[A-Z]{3}-\\d{4}$' }, qty: { type: 'integer', minimum: 1 } },
      },
    },
  },
};

An error inside an item names the exact path, for example body/items/1/qty must be >= 1. The numbers in the path are array indexes, which makes errors easy to find in large payloads. Always set maxItems on arrays that come from clients; otherwise one request can carry a million items.

Reacting to a validation failure

By default a failed validation produces the standard 400 response. Two tools let you do something else.

1. One error handler for everything. When validation fails, Fastify creates an error whose validation property is an array of problems and whose validationContext says which part failed ('body', 'querystring', 'params' or 'headers'). Inside setErrorHandler you can recognize it and shape your own response:

JavaScript
app.setErrorHandler((error, request, reply) => {
  if (error.validation) {
    return reply.code(422).send({
      ok: false,
      problems: error.validation.map((v) => ({ where: error.validationContext, path: v.instancePath, rule: v.keyword })),
    });
  }
  reply.send(error);
});

2. attachValidation: true. Setting this route option stops Fastify from throwing. Instead, the handler runs and request.validationError holds the error (or is undefined when everything is fine). Use it when the same route must do something useful with bad input, such as re-showing a form with messages.

Node.js attachValidation and a validation-aware error handler

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 handler is the usual choice for JSON APIs: one place defines how every validation failure looks. attachValidation is for the few routes that need custom control. Remember that with it, your handler must check request.validationError; forgetting that check means the handler runs with unvalidated data.

Validation versus business rules

A schema answers "is the data well-formed?" It cannot answer "does this project exist?" or "is this email already registered?" Those checks need a database and belong in the handler (or a preHandler hook), where you throw errors such as 404 or 409. A good split is:

  • Schema: types, ranges, formats, required keys, array sizes.
  • Handler: existence, uniqueness, permissions, rules that involve other data.

Common mistakes

  • additionalProperties: false on a headers schema, which rejects the normal headers every client sends.
  • A body schema on a GET route. There is no body to validate, so Fastify refuses a GET or HEAD route that declares one and throws at startup.
  • Declaring params as string and parsing later. Use integer or a pattern and let Fastify do it.
  • Using attachValidation and not checking the error. That removes the safety net completely.
  • Validating unbounded input. Set limits (maxLength, maxItems, maximum); an unbounded schema is only half a defense. The server-wide bodyLimit (1 MiB by default) is the outer wall.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In which order does Fastify validate the request parts?

    Fastify checks headers first, then params, querystring and finally body. The first failure ends validation.
  2. 2. How should a header named X-Api-Version be written in a headers schema?

    Node.js lowercases incoming header names, so the schema must use lowercase keys.
  3. 3. What does the route option attachValidation: true do?

    With attachValidation Fastify does not throw. The handler runs and must check request.validationError itself.
  4. 4. Which check belongs in the handler rather than in the schema?

    Uniqueness needs data from your database. Schemas only describe the shape of one request.
  5. 5. Which property of the validation error says which part of the request failed?

    validationContext is 'body', 'querystring', 'params' or 'headers'; error.validation holds the individual problems.

Summary

  • A route can validate headers, params, querystring and body in one schema object; they are checked in that order.
  • Declare types (integer, boolean, array) for params and query values so coercion hands the handler real numbers and booleans.
  • Header names in schemas are lowercase; never forbid additional properties on headers.
  • Handle failures centrally with setErrorHandler and error.validation / error.validationContext, or use attachValidation for special routes.
  • Schemas check shape and limits; existence, uniqueness and permissions are handler logic.

Next: Shared Schemas and $ref