Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 39 ยท Schemas and Validation

Validation Errors and Formatting

Customize Fastify validation errors: read error.validation, use schemaErrorFormatter, return field-level messages, tune Ajv options and swap the validator.

The default validation message, body/age must be >= 0, is precise but terse. It is written for developers. A mobile app wants a field name and a friendly sentence; a public API may promise a documented error format; a form page may need all the problems at once. This lesson shows what information a validation error carries, three ways to reshape it, and how to change the validator's own settings.

You should already know how to validate request parts.

Anatomy of a validation error

When validation fails, Fastify builds an Error and attaches extra properties:

Property Example Meaning
message body/age must be >= 0 The default human-readable text
statusCode 400 HTTP status
code FST_ERR_VALIDATION Stable machine-readable code
validationContext 'body' Which part failed: body, querystring, params, headers
validation [{ instancePath: '/age', keyword: 'minimum', message: 'must be >= 0', params: {...} }] Array of Ajv problem objects

Each Ajv problem object has instancePath (where in the data, a JSON Pointer like /items/1/qty), keyword (which rule failed, such as required, minLength, format), message and params (rule details, e.g. { limit: 0 } or { missingProperty: 'age' }). The keyword is the part you should build logic on; messages may change between versions.

Way 1: schemaErrorFormatter

The schemaErrorFormatter server option builds the message. Fastify passes the list of Ajv problems and the name of the part (dataVar) and expects an Error back:

JavaScript
const app = Fastify({
  schemaErrorFormatter(errors, dataVar) {
    const first = errors[0];
    const field = first.instancePath.replace(/^\//, '').replaceAll('/', '.') || dataVar;
    return new Error(`Invalid value for "${field}": ${first.message}`);
  },
});

Fastify keeps the status 400 and the FST_ERR_VALIDATION code; only the text changes. The formatter can also be set per plugin (it is encapsulated, like other settings) with app.setSchemaErrorFormatter(fn), which is handy when an admin API and a public API need different wording.

Node.js A friendlier message with schemaErrorFormatter

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.

Way 2: field-level errors from the error handler

For forms you want a map of field -> message, so the UI can mark each input. Build it inside setErrorHandler from error.validation. Because a handler can see every problem object, you can write a small translation table keyed by keyword:

Node.js A field-to-message map in setErrorHandler

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 stand-in (like Ajv's default) reports one problem per request, so each response lists one field. To report every failing field at once, configure Ajv with allErrors: true (next section); your handler code stays the same because it already loops over error.validation.

allErrors: true makes validation slower and, on schemas with many pattern or oneOf rules, can be abused for denial-of-service by a client that sends deliberately bad data. Fastify leaves it off by default. If you turn it on, keep schemas simple and maxItems/maxLength tight.

Way 3: a standard error envelope

Many teams standardize all errors, not just validation ones, in a single shape such as { type, title, status, detail, errors } (the idea behind RFC 9457 "Problem Details"). Do this once in setErrorHandler, branching on error.validation, error.statusCode and your own error classes (see Async Handlers and Error Handling). The benefit is that clients write one error parser.

Configuring Ajv

Fastify builds its default validator with these Ajv options: coerceTypes: 'array', useDefaults: true, removeAdditional: true, allErrors: false. You can override them with the ajv server option. This code needs real packages, so it is read-only here:

JavaScript
import Fastify from 'fastify';
import ajvErrors from 'ajv-errors';

const app = Fastify({
  ajv: {
    customOptions: {
      removeAdditional: false,   // report unknown keys instead of stripping them
      coerceTypes: false,        // be strict: "5" is not a number
      allErrors: true,           // collect every problem (see the warning above)
    },
    plugins: [ajvErrors],        // enables `errorMessage` in schemas
  },
});

With removeAdditional: false and additionalProperties: false, an unknown key becomes a real 400 error (body must NOT have additional properties). With coerceTypes: false the strings in a query string would never match integer, so only turn coercion off for JSON bodies, which brings us to per-route control.

Replacing the validator completely

A route (or the whole app) can use a different validation library through setValidatorCompiler. You give Fastify a function that receives { schema, method, url, httpPart } and returns a function (data) => ({ value }) or ({ error }):

JavaScript
import { z } from 'zod';

app.setValidatorCompiler(({ schema }) => (data) => {
  const result = schema.safeParse(data);
  return result.success ? { value: result.data } : { error: result.error };
});

app.post('/items', { schema: { body: z.object({ name: z.string().min(1) }) } }, handler);

This is how Zod, Joi, Yup and similar libraries plug in. The next lesson shows the most popular route for TypeScript users: TypeBox, which stays inside JSON Schema and gives you static types for free.

Common mistakes

  • Parsing message text in clients. Messages are for humans. Clients should read code, and server-side formatters should use keyword and instancePath.
  • Leaking too much. Validation errors only describe the client's own input, so they are safe to show. Do not use the same handler path to reveal 500 error messages.
  • Turning off removeAdditional globally and then wondering why existing clients that send extra harmless fields now get 400s. Change defaults deliberately, and per plugin if possible.
  • Different error shapes per route. Pick one envelope and enforce it in one handler.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which error property tells you which request part failed validation?

    validationContext is 'body', 'querystring', 'params' or 'headers'. instancePath belongs to the individual Ajv problem objects inside error.validation.
  2. 2. What does the schemaErrorFormatter option return?

    The formatter receives (errors, dataVar) and returns an Error. Fastify keeps status 400 and the FST_ERR_VALIDATION code.
  3. 3. Why is allErrors: true off by default?

    Collecting every problem costs more time per request and makes denial-of-service attempts easier, so it is opt-in.
  4. 4. Which keyword on a problem object is the best thing to switch on when you map errors to friendly messages?

    keyword (required, minLength, format, ...) is stable. Message text can change between library versions.
  5. 5. How can a Fastify app use Zod instead of Ajv for validation?

    setValidatorCompiler lets you plug any validation library into the same schema option.

Summary

  • A validation error has statusCode 400, code FST_ERR_VALIDATION, validationContext and an error.validation array of Ajv problems (instancePath, keyword, message, params).
  • Reword messages with schemaErrorFormatter, or build field maps and standard envelopes in setErrorHandler.
  • Fastify's Ajv defaults are coerceTypes, useDefaults, removeAdditional on and allErrors off; override them through the ajv option.
  • setValidatorCompiler swaps in another validator such as Zod.
  • Programs should read code and keyword, never parse message text.

Next: Type Providers and TypeBox