Validation and Serialization

Fastify uses a schema-based approach, and even if it is not mandatory we recommend using JSON Schema to validate your routes and serialize your outputs. Internally, Fastify compiles the schema into a highly performant function.

⚠ Security Notice

Treat the schema definition as application code. As both validation and serialization features dynamically evaluate code with new Function(), it is not safe to use user-provided schemas. See Ajv and fast-json-stringify for more details.

Validation

The route validation internally relies upon Ajv, which is a high-performance JSON schema validator. Validating the input is very easy: just add the fields that you need inside the route schema, and you are done! The supported validations are:

  • body: validates the body of the request if it is a POST or a PUT.
  • querystring or query: validates the query string. This can be a complete JSON Schema object (with a type property of 'object' and a 'properties' object containing parameters) or a simpler variation in which the type and properties attributes are forgone and the query parameters are listed at the top level (see the example below).
  • params: validates the route params.
  • headers: validates the request headers.

Example:

  1. const bodyJsonSchema = {
  2. type: 'object',
  3. required: ['requiredKey'],
  4. properties: {
  5. someKey: { type: 'string' },
  6. someOtherKey: { type: 'number' },
  7. requiredKey: {
  8. type: 'array',
  9. maxItems: 3,
  10. items: { type: 'integer' }
  11. },
  12. nullableKey: { type: ['number', 'null'] }, // or { type: 'number', nullable: true }
  13. multipleTypesKey: { type: ['boolean', 'number'] },
  14. multipleRestrictedTypesKey: {
  15. oneOf: [
  16. { type: 'string', maxLength: 5 },
  17. { type: 'number', minimum: 10 }
  18. ]
  19. },
  20. enumKey: {
  21. type: 'string',
  22. enum: ['John', 'Foo']
  23. },
  24. notTypeKey: {
  25. not: { type: 'array' }
  26. }
  27. }
  28. }
  29. const queryStringJsonSchema = {
  30. type: 'object',
  31. required: ['name']
  32. properties: {
  33. name: { type: 'string' },
  34. excitement: { type: 'integer' }
  35. }
  36. }
  37. /* If you don't need required query strings,
  38. * A short hand syntax is also there:
  39. const queryStringJsonSchema = {
  40. name: { type: 'string' },
  41. excitement: { type: 'integer' }
  42. }
  43. */
  44. const paramsJsonSchema = {
  45. type: 'object',
  46. properties: {
  47. par1: { type: 'string' },
  48. par2: { type: 'number' }
  49. }
  50. }
  51. const headersJsonSchema = {
  52. type: 'object',
  53. properties: {
  54. 'x-foo': { type: 'string' }
  55. },
  56. required: ['x-foo']
  57. }
  58. const schema = {
  59. body: bodyJsonSchema,
  60. querystring: queryStringJsonSchema,
  61. params: paramsJsonSchema,
  62. headers: headersJsonSchema
  63. }
  64. fastify.post('/the/url', { schema }, handler)

Note that Ajv will try to coerce the values to the types specified in your schema type keywords, both to pass the validation and to use the correctly typed data afterwards.

Adding a shared schema

Thanks to the addSchema API, you can add multiple schemas to the Fastify instance and then reuse them in multiple parts of your application. As usual, this API is encapsulated.

There are two ways to reuse your shared schemas:

  • $ref-way: as described in the standard, you can refer to an external schema. To use it you have to addSchema with a valid $id absolute URI.
  • replace-way: this is a Fastify utility that lets you to substitute some fields with a shared schema. To use it you have to addSchema with an $id having a relative URI fragment which is a simple string that applies only to alphanumeric chars [A-Za-z0-9].

Here an overview on how to set an $id and how references to it:

More examples:

$ref-way usage examples:

  1. fastify.addSchema({
  2. $id: 'http://example.com/common.json',
  3. type: 'object',
  4. properties: {
  5. hello: { type: 'string' }
  6. }
  7. })
  8. fastify.route({
  9. method: 'POST',
  10. url: '/',
  11. schema: {
  12. body: {
  13. type: 'array',
  14. items: { $ref: 'http://example.com/common.json#/properties/hello' }
  15. }
  16. },
  17. handler: () => {}
  18. })

replace-way usage examples:

  1. const fastify = require('fastify')()
  2. fastify.addSchema({
  3. $id: 'greetings',
  4. type: 'object',
  5. properties: {
  6. hello: { type: 'string' }
  7. }
  8. })
  9. fastify.route({
  10. method: 'POST',
  11. url: '/',
  12. schema: {
  13. body: 'greetings#'
  14. },
  15. handler: () => {}
  16. })
  17. fastify.register((instance, opts, done) => {
  18. /**
  19. * In children's scope can use schemas defined in upper scope like 'greetings'.
  20. * Parent scope can't use the children schemas.
  21. */
  22. instance.addSchema({
  23. $id: 'framework',
  24. type: 'object',
  25. properties: {
  26. fastest: { type: 'string' },
  27. hi: 'greetings#'
  28. }
  29. })
  30. instance.route({
  31. method: 'POST',
  32. url: '/sub',
  33. schema: {
  34. body: 'framework#'
  35. },
  36. handler: () => {}
  37. })
  38. done()
  39. })

You can use the shared schema everywhere, as top level schema or nested inside other schemas:

  1. const fastify = require('fastify')()
  2. fastify.addSchema({
  3. $id: 'greetings',
  4. type: 'object',
  5. properties: {
  6. hello: { type: 'string' }
  7. }
  8. })
  9. fastify.route({
  10. method: 'POST',
  11. url: '/',
  12. schema: {
  13. body: {
  14. type: 'object',
  15. properties: {
  16. greeting: 'greetings#',
  17. timestamp: { type: 'number' }
  18. }
  19. }
  20. },
  21. handler: () => {}
  22. })

Retrieving a copy of shared schemas

The function getSchemas returns the shared schemas available in the selected scope:

  1. fastify.addSchema({ $id: 'one', my: 'hello' })
  2. fastify.get('/', (request, reply) => { reply.send(fastify.getSchemas()) })
  3. fastify.register((instance, opts, done) => {
  4. instance.addSchema({ $id: 'two', my: 'ciao' })
  5. instance.get('/sub', (request, reply) => { reply.send(instance.getSchemas()) })
  6. instance.register((subinstance, opts, done) => {
  7. subinstance.addSchema({ $id: 'three', my: 'hola' })
  8. subinstance.get('/deep', (request, reply) => { reply.send(subinstance.getSchemas()) })
  9. done()
  10. })
  11. done()
  12. })

This example will returns:

URLSchemas
/one
/subone, two
/deepone, two, three

Ajv Plugins

You can provide a list of plugins you want to use with Ajv:

Refer to ajv options to check plugins format

  1. const fastify = require('fastify')({
  2. ajv: {
  3. plugins: [
  4. require('ajv-merge-patch')
  5. ]
  6. }
  7. })
  8. fastify.route({
  9. method: 'POST',
  10. url: '/',
  11. schema: {
  12. body: {
  13. $patch: {
  14. source: {
  15. type: 'object',
  16. properties: {
  17. q: {
  18. type: 'string'
  19. }
  20. }
  21. },
  22. with: [
  23. {
  24. op: 'add',
  25. path: '/properties/q',
  26. value: { type: 'number' }
  27. }
  28. ]
  29. }
  30. }
  31. },
  32. handler (req, reply) {
  33. reply.send({ ok: 1 })
  34. }
  35. })
  36. fastify.route({
  37. method: 'POST',
  38. url: '/',
  39. schema: {
  40. body: {
  41. $merge: {
  42. source: {
  43. type: 'object',
  44. properties: {
  45. q: {
  46. type: 'string'
  47. }
  48. }
  49. },
  50. with: {
  51. required: ['q']
  52. }
  53. }
  54. }
  55. },
  56. handler (req, reply) {
  57. reply.send({ ok: 1 })
  58. }
  59. })

Schema Compiler

The schemaCompiler is a function that returns a function that validates the body, url parameters, headers, and query string. The default schemaCompiler returns a function that implements the ajv validation interface. Fastify uses it internally to speed the validation up.

Fastify's baseline ajv configuration is:

  1. {
  2. removeAdditional: true, // remove additional properties
  3. useDefaults: true, // replace missing properties and items with the values from corresponding default keyword
  4. coerceTypes: true, // change data type of data to match type keyword
  5. allErrors: true, // check for all errors
  6. nullable: true // support keyword "nullable" from Open API 3 specification.
  7. }

This baseline configuration can be modified by providing ajv.customOptions to your Fastify factory.

If you want to change or set additional config options, you will need to create your own instance and override the existing one like:

  1. const fastify = require('fastify')()
  2. const Ajv = require('ajv')
  3. const ajv = new Ajv({
  4. // the fastify defaults (if needed)
  5. removeAdditional: true,
  6. useDefaults: true,
  7. coerceTypes: true,
  8. allErrors: true,
  9. nullable: true,
  10. // any other options
  11. // ...
  12. })
  13. fastify.setSchemaCompiler(function (schema) {
  14. return ajv.compile(schema)
  15. })
  16. // -------
  17. // Alternatively, you can set the schema compiler using the setter property:
  18. fastify.schemaCompiler = function (schema) { return ajv.compile(schema) })

Note: If you use a custom instance of any validator (even Ajv), you have to add schemas to the validator instead of fastify, since fastify's default validator is no longer used, and fastify's addSchema method has no idea what validator you are using.

Using other validation libraries

The schemaCompiler function makes it easy to substitute ajv with almost any Javascript validation library (joi, yup, …).

However, in order to make your chosen validation engine play well with Fastify's request/response pipeline, the function returned by your schemaCompiler function should return an object with either :

  • in case of validation failure: an error property, filled with an instance of Error or a string that describes the validation error
  • in case of validation success: an value property, filled with the coerced value that passed the validation

The examples below are therefore equivalent:

  1. const joi = require('joi')
  2. // Validation options to match ajv's baseline options used in Fastify
  3. const joiOptions = {
  4. abortEarly: false, // return all errors
  5. convert: true, // change data type of data to match type keyword
  6. allowUnknown : false, // remove additional properties
  7. noDefaults: false
  8. }
  9. const joiBodySchema = joi.object().keys({
  10. age: joi.number().integer().required(),
  11. sub: joi.object().keys({
  12. name: joi.string().required()
  13. }).required()
  14. })
  15. const joiSchemaCompiler = schema => data => {
  16. // joi `validate` function returns an object with an error property (if validation failed) and a value property (always present, coerced value if validation was successful)
  17. const { error, value } = joiSchema.validate(data, joiOptions)
  18. if (error) {
  19. return { error }
  20. } else {
  21. return { value }
  22. }
  23. }
  24. // or more simply...
  25. const joiSchemaCompiler = schema => data => joiSchema.validate(data, joiOptions)
  26. fastify.post('/the/url', {
  27. schema: {
  28. body: joiBodySchema
  29. },
  30. schemaCompiler: joiSchemaCompiler
  31. }, handler)
  1. const yup = require('yup')
  2. // Validation options to match ajv's baseline options used in Fastify
  3. const yupOptions = {
  4. strict: false,
  5. abortEarly: false, // return all errors
  6. stripUnknown: true, // remove additional properties
  7. recursive: true
  8. }
  9. const yupBodySchema = yup.object({
  10. age: yup.number().integer().required(),
  11. sub: yup.object().shape({
  12. name: yup.string().required()
  13. }).required()
  14. })
  15. const yupSchemaCompiler = schema => data => {
  16. // with option strict = false, yup `validateSync` function returns the coerced value if validation was successful, or throws if validation failed
  17. try {
  18. const result = schema.validateSync(data, yupOptions)
  19. return { value: result }
  20. } catch (e) {
  21. return { error: e }
  22. }
  23. }
  24. fastify.post('/the/url', {
  25. schema: {
  26. body: yupBodySchema
  27. },
  28. schemaCompiler: yupSchemaCompiler
  29. }, handler)
Validation messages with other validation libraries

Fastify's validation error messages are tightly coupled to the default validation engine: errors returned from ajv are eventually run through the schemaErrorsText function which is responsible for building human-friendly error messages. However, the schemaErrorsText function is written with ajv in mind : as a result, you may run into odd or incomplete error messages when using other validation librairies.

To circumvent this issue, you have 2 main options :

  • make sure your validation function (returned by your custom schemaCompiler) returns errors in the exact same structure and format as ajv (although this could prove to be difficult and tricky due to differences between validation engines)
  • or use a custom errorHandler to intercept and format your 'custom' validation errorsTo help you in writing a custom errorHandler, Fastify adds 2 properties to all validation errors:
  • validation: the content of the error property of the object returned by the validation function (returned by your custom schemaCompiler)
  • validationContext: the 'context' (body, params, query, headers) where the validation error occurred

A very contrived example of such a custom errorHandler handling validation errors is shown below:

  1. const errorHandler = (error, request, reply) => {
  2. const statusCode = error.statusCode
  3. let response
  4. const { validation, validationContext } = error
  5. // check if we have a validation error
  6. if (validation) {
  7. response = {
  8. message: `A validation error occured when validating the ${validationContext}...`, // validationContext will be 'body' or 'params' or 'headers' or 'query'
  9. errors: validation // this is the result of your validation library...
  10. }
  11. } else {
  12. response = {
  13. message: 'An error occurred...'
  14. }
  15. }
  16. // any additional work here, eg. log error
  17. // ...
  18. reply.status(statusCode).send(response)
  19. }

Schema Resolver

The schemaResolver is a function that works together with the schemaCompiler: you can't use it with the default schema compiler. This feature is useful when you use complex schemas with $ref keyword in your routes and a custom validator.

This is needed because all the schemas you add to your custom compiler are unknown to Fastify but it need to resolve the $ref paths.

  1. const fastify = require('fastify')()
  2. const Ajv = require('ajv')
  3. const ajv = new Ajv()
  4. ajv.addSchema({
  5. $id: 'urn:schema:foo',
  6. definitions: {
  7. foo: { type: 'string' }
  8. },
  9. type: 'object',
  10. properties: {
  11. foo: { $ref: '#/definitions/foo' }
  12. }
  13. })
  14. ajv.addSchema({
  15. $id: 'urn:schema:response',
  16. type: 'object',
  17. required: ['foo'],
  18. properties: {
  19. foo: { $ref: 'urn:schema:foo#/definitions/foo' }
  20. }
  21. })
  22. ajv.addSchema({
  23. $id: 'urn:schema:request',
  24. type: 'object',
  25. required: ['foo'],
  26. properties: {
  27. foo: { $ref: 'urn:schema:foo#/definitions/foo' }
  28. }
  29. })
  30. fastify.setSchemaCompiler(schema => ajv.compile(schema))
  31. fastify.setSchemaResolver((ref) => {
  32. return ajv.getSchema(ref).schema
  33. })
  34. fastify.route({
  35. method: 'POST',
  36. url: '/',
  37. schema: {
  38. body: ajv.getSchema('urn:schema:request').schema,
  39. response: {
  40. '2xx': ajv.getSchema('urn:schema:response').schema
  41. }
  42. },
  43. handler (req, reply) {
  44. reply.send({ foo: 'bar' })
  45. }
  46. })

Serialization

Usually you will send your data to the clients via JSON, and Fastify has a powerful tool to help you, fast-json-stringify, which is used if you have provided an output schema in the route options. We encourage you to use an output schema, as it will increase your throughput by 100-400% depending on your payload and will prevent accidental disclosure of sensitive information.

Example:

  1. const schema = {
  2. response: {
  3. 200: {
  4. type: 'object',
  5. properties: {
  6. value: { type: 'string' },
  7. otherValue: { type: 'boolean' }
  8. }
  9. }
  10. }
  11. }
  12. fastify.post('/the/url', { schema }, handler)

As you can see, the response schema is based on the status code. If you want to use the same schema for multiple status codes, you can use '2xx', for example:

  1. const schema = {
  2. response: {
  3. '2xx': {
  4. type: 'object',
  5. properties: {
  6. value: { type: 'string' },
  7. otherValue: { type: 'boolean' }
  8. }
  9. },
  10. 201: {
  11. type: 'object',
  12. properties: {
  13. value: { type: 'string' }
  14. }
  15. }
  16. }
  17. }
  18. fastify.post('/the/url', { schema }, handler)

If you need a custom serializer in a very specific part of your code, you can set one with reply.serializer(…).

Error Handling

When schema validation fails for a request, Fastify will automtically return a status 400 response including the result from the validator in the payload. As an example, if you have the following schema for your route

  1. const schema = {
  2. body: {
  3. type: 'object',
  4. properties: {
  5. name: { type: 'string' }
  6. },
  7. required: ['name']
  8. }
  9. }

and fail to satisfy it, the route will immediately return a response with the following payload

  1. {
  2. "statusCode": 400,
  3. "error": "Bad Request",
  4. "message": "body should have required property 'name'"
  5. }

If you want to handle errors inside the route, you can specify the attachValidation option for your route. If there is a validation error, the validationError property of the request will contain the Error object with the raw validation result as shown below

  1. const fastify = Fastify()
  2. fastify.post('/', { schema, attachValidation: true }, function (req, reply) {
  3. if (req.validationError) {
  4. // `req.validationError.validation` contains the raw validation error
  5. reply.code(400).send(req.validationError)
  6. }
  7. })

You can also use setErrorHandler to define a custom response for validation errors such as

  1. fastify.setErrorHandler(function (error, request, reply) {
  2. if (error.validation) {
  3. // error.validationContext can be on of [body, params, querystring, headers]
  4. reply.status(422).send(new Error(`validation failed of the ${error.validationContext}`))
  5. }
  6. })

If you want custom error response in schema without headaches and quickly, you can take a look at here

JSON Schema and Shared Schema support

JSON Schema has some type of utilities in order to optimize your schemas that, in conjuction with the Fastify's shared schema, let you reuse all your schemas easily.

Use CaseValidatorSerializer
shared schema✔️✔️
$ref to $id️️✔️✔️
$ref to /definitions✔️✔️
$ref to shared schema $id✔️✔️
$ref to shared schema /definitions✔️✔️

Examples

  1. // Usage of the Shared Schema feature
  2. fastify.addSchema({
  3. $id: 'sharedAddress',
  4. type: 'object',
  5. properties: {
  6. city: { 'type': 'string' }
  7. }
  8. })
  9. const sharedSchema = {
  10. type: 'object',
  11. properties: {
  12. home: 'sharedAddress#',
  13. work: 'sharedAddress#'
  14. }
  15. }
  1. // Usage of $ref to $id in same JSON Schema
  2. const refToId = {
  3. type: 'object',
  4. definitions: {
  5. foo: {
  6. $id: '#address',
  7. type: 'object',
  8. properties: {
  9. city: { 'type': 'string' }
  10. }
  11. }
  12. },
  13. properties: {
  14. home: { $ref: '#address' },
  15. work: { $ref: '#address' }
  16. }
  17. }
  1. // Usage of $ref to /definitions in same JSON Schema
  2. const refToDefinitions = {
  3. type: 'object',
  4. definitions: {
  5. foo: {
  6. $id: '#address',
  7. type: 'object',
  8. properties: {
  9. city: { 'type': 'string' }
  10. }
  11. }
  12. },
  13. properties: {
  14. home: { $ref: '#/definitions/foo' },
  15. work: { $ref: '#/definitions/foo' }
  16. }
  17. }
  1. // Usage $ref to a shared schema $id as external schema
  2. fastify.addSchema({
  3. $id: 'http://foo/common.json',
  4. type: 'object',
  5. definitions: {
  6. foo: {
  7. $id: '#address',
  8. type: 'object',
  9. properties: {
  10. city: { 'type': 'string' }
  11. }
  12. }
  13. }
  14. })
  15. const refToSharedSchemaId = {
  16. type: 'object',
  17. properties: {
  18. home: { $ref: 'http://foo/common.json#address' },
  19. work: { $ref: 'http://foo/common.json#address' }
  20. }
  21. }
  1. // Usage $ref to a shared schema /definitions as external schema
  2. fastify.addSchema({
  3. $id: 'http://foo/common.json',
  4. type: 'object',
  5. definitions: {
  6. foo: {
  7. type: 'object',
  8. properties: {
  9. city: { 'type': 'string' }
  10. }
  11. }
  12. }
  13. })
  14. const refToSharedSchemaDefinitions = {
  15. type: 'object',
  16. properties: {
  17. home: { $ref: 'http://foo/common.json#/definitions/foo' },
  18. work: { $ref: 'http://foo/common.json#/definitions/foo' }
  19. }
  20. }

Resources