Factory

The Fastify module exports a factory function that is used to create new **Fastify server** instances. This factory function accepts an options object which is used to customize the resulting instance. This document describes the properties available in that options object.

http2

If true Node.js core’s HTTP/2 module is used for binding the socket.

  • Default: false

https

An object used to configure the server’s listening socket for TLS. The options are the same as the Node.js core createServer method. When this property is null, the socket will not be configured for TLS.

This option also applies when the http2 option is set.

  • Default: null

connectionTimeout

Defines the server timeout in milliseconds. See documentation for server.timeout property to understand the effect of this option. When serverFactory option is specified, this option is ignored.

  • Default: 0 (no timeout)

keepAliveTimeout

Defines the server keep-alive timeout in milliseconds. See documentation for server.keepAliveTimeout property to understand the effect of this option. This option only applies when HTTP/1 is in use. Also, when serverFactory option is specified, this option is ignored.

  • Default: 5000 (5 seconds)

maxRequestsPerSocket

Defines the maximum number of requests socket can handle before closing keep alive connection. See documentation for server.maxRequestsPerSocket property to understand the effect of this option. This option only applies when HTTP/1.1 is in use. Also, when serverFactory option is specified, this option is ignored.

At the time of this writing, only node version greater or equal to 16.10.0 support this option. Check the Node.js documentation for availability in the version you are running.

  • Default: 0 (no limit)

requestTimeout

Defines the maximum number of milliseconds for receiving the entire request from the client. server.requestTimeout property to understand the effect of this option. Also, when serverFactory option is specified, this option is ignored. It must be set to a non-zero value (e.g. 120 seconds) to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front.

At the time of this writing, only node version greater or equal to 14.11.0 support this option. Check the Node.js documentation for availability in the version you are running.

  • Default: 0 (no limit)

ignoreTrailingSlash

Fastify uses find-my-way to handle routing. This option may be set to true to ignore trailing slashes in routes. This option applies to all route registrations for the resulting server instance.

  • Default: false
  1. const fastify = require('fastify')({
  2. ignoreTrailingSlash: true
  3. })
  4. // registers both "/foo" and "/foo/"
  5. fastify.get('/foo/', function (req, reply) {
  6. reply.send('foo')
  7. })
  8. // registers both "/bar" and "/bar/"
  9. fastify.get('/bar', function (req, reply) {
  10. reply.send('bar')
  11. })

maxParamLength

You can set a custom length for parameters in parametric (standard, regex, and multi) routes by using maxParamLength option; the default value is 100 characters.

This can be useful especially if you have some regex based route, protecting you against DoS attacks.

If the maximum length limit is reached, the not found route will be invoked.

bodyLimit

Defines the maximum payload, in bytes, the server is allowed to accept.

  • Default: 1048576 (1MiB)

onProtoPoisoning

Defines what action the framework must take when parsing a JSON object with __proto__. This functionality is provided by secure-json-parse. See Prototype Poisoning for more details about prototype poisoning attacks.

Possible values are 'error', 'remove' and 'ignore'.

  • Default: 'error'

onConstructorPoisoning

Defines what action the framework must take when parsing a JSON object with constructor. This functionality is provided by secure-json-parse. See Prototype Poisoning for more details about prototype poisoning attacks.

Possible values are 'error', 'remove' and 'ignore'.

  • Default: 'error'

logger

Fastify includes built-in logging via the Pino logger. This property is used to configure the internal logger instance.

The possible values this property may have are:

  • Default: false. The logger is disabled. All logging methods will point to a null logger abstract-logging instance.

  • pinoInstance: a previously instantiated instance of Pino. The internal logger will point to this instance.

  • object: a standard Pino options object. This will be passed directly to the Pino constructor. If the following properties are not present on the object, they will be added accordingly:

    • level: the minimum logging level. If not set, it will be set to 'info'.
    • serializers: a hash of serialization functions. By default, serializers are added for req (incoming request objects), res (outgoing response objects), and err (standard Error objects). When a log method receives an object with any of these properties then the respective serializer will be used for that property. For example:

      1. fastify.get('/foo', function (req, res) {
      2. req.log.info({req}) // log the serialized request object
      3. res.send('foo')
      4. })

      Any user-supplied serializer will override the default serializer of the corresponding property.

  • loggerInstance: a custom logger instance. The logger must conform to the Pino interface by having the following methods: info, error, debug, fatal, warn, trace, child. For example:

    1. const pino = require('pino')();
    2. const customLogger = {
    3. info: function (o, ...n) {},
    4. warn: function (o, ...n) {},
    5. error: function (o, ...n) {},
    6. fatal: function (o, ...n) {},
    7. trace: function (o, ...n) {},
    8. debug: function (o, ...n) {},
    9. child: function() {
    10. const child = Object.create(this);
    11. child.pino = pino.child(...arguments);
    12. return child;
    13. },
    14. };
    15. const fastify = require('fastify')({logger: customLogger});

disableRequestLogging

By default, when logging is enabled, Fastify will issue an info level log message when a request is received and when the response for that request has been sent. By setting this option to true, these log messages will be disabled. This allows for more flexible request start and end logging by attaching custom onRequest and onResponse hooks.

  • Default: false
  1. // Examples of hooks to replicate the disabled functionality.
  2. fastify.addHook('onRequest', (req, reply, done) => {
  3. req.log.info({ url: req.raw.url, id: req.id }, 'received request')
  4. done()
  5. })
  6. fastify.addHook('onResponse', (req, reply, done) => {
  7. req.log.info({ url: req.raw.originalUrl, statusCode: reply.raw.statusCode }, 'request completed')
  8. done()
  9. })

Please note that this setting will also disable an error log written by the default onResponse hook on reply callback errors.

serverFactory

You can pass a custom HTTP server to Fastify by using the serverFactory option.

serverFactory is a function that takes a handler parameter, which takes the request and response objects as parameters, and an options object, which is the same you have passed to Fastify.

  1. const serverFactory = (handler, opts) => {
  2. const server = http.createServer((req, res) => {
  3. handler(req, res)
  4. })
  5. return server
  6. }
  7. const fastify = Fastify({ serverFactory })
  8. fastify.get('/', (req, reply) => {
  9. reply.send({ hello: 'world' })
  10. })
  11. fastify.listen(3000)

Internally Fastify uses the API of Node core HTTP server, so if you are using a custom server you must be sure to have the same API exposed. If not, you can enhance the server instance inside the serverFactory function before the return statement.

jsonShorthand

  • Default: true

Internally, and by default, Fastify will automatically infer the root properties of JSON Schemas if it does not find valid root properties according to the JSON Schema spec. If you wish to implement your own schema validation compiler, for example: to parse schemas as JTD instead of JSON Schema, then you can explicitly set this option to false to make sure the schemas you receive are unmodified and are not being treated internally as JSON Schema.

  1. const AjvJTD = require('ajv/dist/jtd'/* only valid for AJV v7+ */)
  2. const ajv = new AjvJTD({
  3. // This would let you throw at start for invalid JTD schema objects
  4. allErrors: process.env.NODE_ENV === 'development'
  5. })
  6. const fastify = Fastify({ jsonShorthand: false })
  7. fastify.setValidatorCompiler(({ schema }) => {
  8. return ajv.compile(schema)
  9. })
  10. fastify.post('/', {
  11. schema: {
  12. body: {
  13. properties: {
  14. foo: { type: 'uint8' }
  15. }
  16. }
  17. },
  18. handler (req, reply) { reply.send({ ok: 1 }) }
  19. })

Note: Fastify does not currently throw on invalid schemas, so if you turn this off in an existing project, you need to be careful that none of your existing schemas become invalid as a result, since they will be treated as a catch-all.

caseSensitive

By default, value equal to true, routes are registered as case sensitive. That is, /foo is not equivalent to /Foo. When set to false, routes are registered in a fashion such that /foo is equivalent to /Foo which is equivalent to /FOO.

By setting caseSensitive to false, all paths will be matched as lowercase, but the route parameters or wildcards will maintain their original letter casing.

  1. fastify.get('/user/:username', (request, reply) => {
  2. // Given the URL: /USER/NodeJS
  3. console.log(request.params.username) // -> 'NodeJS'
  4. })

Please note that setting this option to false goes against RFC3986.

Also note, this setting will not affect query strings. If you want to change the way query strings are handled take a look at querystringParser.

requestIdHeader

The header name used to know the request-id. See the request-id section.

  • Default: 'request-id'

requestIdLogLabel

Defines the label used for the request identifier when logging the request.

  • Default: 'reqId'

genReqId

Function for generating the request-id. It will receive the incoming request as a parameter.

  • Default: value of 'request-id' header if provided or monotonically increasing integers

Especially in distributed systems, you may want to override the default ID generation behavior as shown below. For generating UUIDs you may want to check out hyperid

  1. let i = 0
  2. const fastify = require('fastify')({
  3. genReqId: function (req) { return i++ }
  4. })

Note: genReqId will not be called if the header set in [requestIdHeader](#requestidheader) is available (defaults to ‘request-id’).

trustProxy

By enabling the trustProxy option, Fastify will know that it is sitting behind a proxy and that the X-Forwarded-* header fields may be trusted, which otherwise may be easily spoofed.

  1. const fastify = Fastify({ trustProxy: true })
  • Default: false
  • true/false: Trust all proxies (true) or do not trust any proxies (false).
  • string: Trust only given IP/CIDR (e.g. '127.0.0.1'). May be a list of comma separated values (e.g. '127.0.0.1,192.168.1.1/24').
  • Array<string>: Trust only given IP/CIDR list (e.g. ['127.0.0.1']).
  • number: Trust the nth hop from the front-facing proxy server as the client.
  • Function: Custom trust function that takes address as first arg

    1. function myTrustFn(address, hop) {
    2. return address === '1.2.3.4' || hop === 1
    3. }

For more examples, refer to the proxy-addr package.

You may access the ip, ips, hostname and protocol values on the request object.

  1. fastify.get('/', (request, reply) => {
  2. console.log(request.ip)
  3. console.log(request.ips)
  4. console.log(request.hostname)
  5. console.log(request.protocol)
  6. })

Note: if a request contains multiple x-forwarded-host or x-forwarded-proto headers, it is only the last one that is used to derive request.hostname and request.protocol

pluginTimeout

The maximum amount of time in milliseconds in which a plugin can load. If not, ready will complete with an Error with code 'ERR_AVVIO_PLUGIN_TIMEOUT'.

  • Default: 10000

querystringParser

The default query string parser that Fastify uses is the Node.js’s core querystring module.

You can change this default setting by passing the option querystringParser and use a custom one, such as qs.

  1. const qs = require('qs')
  2. const fastify = require('fastify')({
  3. querystringParser: str => qs.parse(str)
  4. })

You can also use Fastify’s default parser but change some handling behaviour, like the example below for case insensitive keys and values:

  1. const querystring = require('querystring')
  2. const fastify = require('fastify')({
  3. querystringParser: str => querystring.parse(str.toLowerCase())
  4. })

Note, if you only want the keys (and not the values) to be case insensitive we recommend using a custom parser to convert only the keys to lowercase.

exposeHeadRoutes

Automatically creates a sibling HEAD route for each GET route defined. If you want a custom HEAD handler without disabling this option, make sure to define it before the GET route.

  • Default: false

constraints

Fastify’s built in route constraints are provided by find-my-way, which allow constraining routes by version or host. You are able to add new constraint strategies, or override the built in strategies by providing a constraints object with strategies for find-my-way. You can find more information on constraint strategies in the find-my-way documentation.

  1. const customVersionStrategy = {
  2. storage: function () {
  3. let versions = {}
  4. return {
  5. get: (version) => { return versions[version] || null },
  6. set: (version, store) => { versions[version] = store },
  7. del: (version) => { delete versions[version] },
  8. empty: () => { versions = {} }
  9. }
  10. },
  11. deriveVersion: (req, ctx) => {
  12. return req.headers['accept']
  13. }
  14. }
  15. const fastify = require('fastify')({
  16. constraints: {
  17. version: customVersionStrategy
  18. }
  19. })

return503OnClosing

Returns 503 after calling close server method. If false, the server routes the incoming request as usual.

  • Default: true

ajv

Configure the Ajv v6 instance used by Fastify without providing a custom one.

  • Default:
  1. {
  2. customOptions: {
  3. removeAdditional: true,
  4. useDefaults: true,
  5. coerceTypes: true,
  6. allErrors: false,
  7. nullable: true
  8. },
  9. plugins: []
  10. }
  1. const fastify = require('fastify')({
  2. ajv: {
  3. customOptions: {
  4. nullable: false // Refer to [ajv options](https://github.com/ajv-validator/ajv/tree/v6#options)
  5. },
  6. plugins: [
  7. require('ajv-merge-patch'),
  8. [require('ajv-keywords'), 'instanceof']
  9. // Usage: [plugin, pluginOptions] - Plugin with options
  10. // Usage: plugin - Plugin without options
  11. ]
  12. }
  13. })

serializerOpts

Customize the options of the default fast-json-stringify instance that serialize the response’s payload:

  1. const fastify = require('fastify')({
  2. serializerOpts: {
  3. rounding: 'ceil'
  4. }
  5. })

http2SessionTimeout

Set a default timeout to every incoming HTTP/2 session. The session will be closed on the timeout. Default: 5000 ms.

Note that this is needed to offer the graceful “close” experience when using HTTP/2. The low default has been chosen to mitigate denial of service attacks. When the server is behind a load balancer or can scale automatically this value can be increased to fit the use case. Node core defaults this to 0. `

frameworkErrors

  • Default: null

Fastify provides default error handlers for the most common use cases. It is possible to override one or more of those handlers with custom code using this option.

Note: Only FST_ERR_BAD_URL is implemented at the moment.

  1. const fastify = require('fastify')({
  2. frameworkErrors: function (error, req, res) {
  3. if (error instanceof FST_ERR_BAD_URL) {
  4. res.code(400)
  5. return res.send("Provided url is not valid")
  6. } else {
  7. res.send(err)
  8. }
  9. }
  10. })

clientErrorHandler

Set a clientErrorHandler that listens to error events emitted by client connections and responds with a 400.

It is possible to override the default clientErrorHandler using this option.

  • Default:

    1. function defaultClientErrorHandler (err, socket) {
    2. if (err.code === 'ECONNRESET') {
    3. return
    4. }
    5. const body = JSON.stringify({
    6. error: http.STATUS_CODES['400'],
    7. message: 'Client Error',
    8. statusCode: 400
    9. })
    10. this.log.trace({ err }, 'client error')
    11. if (socket.writable) {
    12. socket.end(`HTTP/1.1 400 Bad Request\r\nContent-Length: ${body.length}\r\nContent-Type: application/json\r\n\r\n${body}`)
    13. }
    14. }

Note: clientErrorHandler operates with raw socket. The handler is expected to return a properly formed HTTP response that includes a status line, HTTP headers and a message body. Before attempting to write the socket, the handler should check if the socket is still writable as it may have already been destroyed.

  1. const fastify = require('fastify')({
  2. clientErrorHandler: function (err, socket) {
  3. const body = JSON.stringify({
  4. error: {
  5. message: 'Client error',
  6. code: '400'
  7. }
  8. })
  9. // `this` is bound to fastify instance
  10. this.log.trace({ err }, 'client error')
  11. // the handler is responsible for generating a valid HTTP response
  12. socket.end(`HTTP/1.1 400 Bad Request\r\nContent-Length: ${body.length}\r\nContent-Type: application/json\r\n\r\n${body}`)
  13. }
  14. })

rewriteUrl

Set a sync callback function that must return a string that allows rewriting URLs.

Rewriting a URL will modify the url property of the req object

  1. function rewriteUrl (req) { // req is the Node.js HTTP request
  2. return req.url === '/hi' ? '/hello' : req.url;
  3. }

Note that rewriteUrl is called before routing, it is not encapsulated and it is an instance-wide configuration.

Instance

Server Methods

server

fastify.server: The Node core server object as returned by the Fastify factory function.

after

Invoked when the current plugin and all the plugins that have been registered within it have finished loading. It is always executed before the method fastify.ready.

  1. fastify
  2. .register((instance, opts, done) => {
  3. console.log('Current plugin')
  4. done()
  5. })
  6. .after(err => {
  7. console.log('After current plugin')
  8. })
  9. .register((instance, opts, done) => {
  10. console.log('Next plugin')
  11. done()
  12. })
  13. .ready(err => {
  14. console.log('Everything has been loaded')
  15. })

In case after() is called without a function, it returns a Promise:

  1. fastify.register(async (instance, opts) => {
  2. console.log('Current plugin')
  3. })
  4. await fastify.after()
  5. console.log('After current plugin')
  6. fastify.register(async (instance, opts) => {
  7. console.log('Next plugin')
  8. })
  9. await fastify.ready()
  10. console.log('Everything has been loaded')

ready

Function called when all the plugins have been loaded. It takes an error parameter if something went wrong.

  1. fastify.ready(err => {
  2. if (err) throw err
  3. })

If it is called without any arguments, it will return a Promise:

  1. fastify.ready().then(() => {
  2. console.log('successfully booted!')
  3. }, (err) => {
  4. console.log('an error happened', err)
  5. })

listen

Starts the server on the given port after all the plugins are loaded, internally waits for the .ready() event. The callback is the same as the Node core. By default, the server will listen on the address resolved by localhost when no specific address is provided (127.0.0.1 or ::1 depending on the operating system). If listening on any available interface is desired, then specifying 0.0.0.0 for the address will listen on all IPv4 addresses. Using :: for the address will listen on all IPv6 addresses and, depending on OS, may also listen on all IPv4 addresses. Be careful when deciding to listen on all interfaces; it comes with inherent security risks.

  1. fastify.listen(3000, (err, address) => {
  2. if (err) {
  3. fastify.log.error(err)
  4. process.exit(1)
  5. }
  6. })

Specifying an address is also supported:

  1. fastify.listen(3000, '127.0.0.1', (err, address) => {
  2. if (err) {
  3. fastify.log.error(err)
  4. process.exit(1)
  5. }
  6. })

Specifying a backlog queue size is also supported:

  1. fastify.listen(3000, '127.0.0.1', 511, (err, address) => {
  2. if (err) {
  3. fastify.log.error(err)
  4. process.exit(1)
  5. }
  6. })

Specifying options is also supported; the object is same as options in the Node.js server listen:

  1. fastify.listen({ port: 3000, host: '127.0.0.1', backlog: 511 }, (err) => {
  2. if (err) {
  3. fastify.log.error(err)
  4. process.exit(1)
  5. }
  6. })

If no callback is provided a Promise is returned:

  1. fastify.listen(3000)
  2. .then((address) => console.log(`server listening on ${address}`))
  3. .catch(err => {
  4. console.log('Error starting server:', err)
  5. process.exit(1)
  6. })

Specifying an address without a callback is also supported:

  1. fastify.listen(3000, '127.0.0.1')
  2. .then((address) => console.log(`server listening on ${address}`))
  3. .catch(err => {
  4. console.log('Error starting server:', err)
  5. process.exit(1)
  6. })

Specifying options without a callback is also supported:

  1. fastify.listen({ port: 3000, host: '127.0.0.1', backlog: 511 })
  2. .then((address) => console.log(`server listening on ${address}`))
  3. .catch(err => {
  4. console.log('Error starting server:', err)
  5. process.exit(1)
  6. })

When deploying to a Docker, and potentially other, containers, it is advisable to listen on 0.0.0.0 because they do not default to exposing mapped ports to localhost:

  1. fastify.listen(3000, '0.0.0.0', (err, address) => {
  2. if (err) {
  3. fastify.log.error(err)
  4. process.exit(1)
  5. }
  6. })

If the port is omitted (or is set to zero), a random available port is automatically chosen (later available via fastify.server.address().port).

The default options of listen are:

  1. fastify.listen({
  2. port: 0,
  3. host: 'localhost',
  4. exclusive: false,
  5. readableAll: false,
  6. writableAll: false,
  7. ipv6Only: false
  8. }, (err) => {})

getDefaultRoute

Method to get the defaultRoute for the server:

  1. const defaultRoute = fastify.getDefaultRoute()

setDefaultRoute

Method to set the defaultRoute for the server:

  1. const defaultRoute = function (req, res) {
  2. res.end('hello world')
  3. }
  4. fastify.setDefaultRoute(defaultRoute)

routing

Method to access the lookup method of the internal router and match the request to the appropriate handler:

  1. fastify.routing(req, res)

route

Method to add routes to the server, it also has shorthand functions, check here.

close

fastify.close(callback): call this function to close the server instance and run the ‘onClose’ hook.

Calling close will also cause the server to respond to every new incoming request with a 503 error and destroy that request. See return503OnClosing flags for changing this behavior.

If it is called without any arguments, it will return a Promise:

  1. fastify.close().then(() => {
  2. console.log('successfully closed!')
  3. }, (err) => {
  4. console.log('an error happened', err)
  5. })

decorate*

Function useful if you need to decorate the fastify instance, Reply or Request, check here.

register

Fastify allows the user to extend its functionality with plugins. A plugin can be a set of routes, a server decorator, or whatever, check here.

addHook

Function to add a specific hook in the lifecycle of Fastify, check here.

prefix

The full path that will be prefixed to a route.

Example:

  1. fastify.register(function (instance, opts, done) {
  2. instance.get('/foo', function (request, reply) {
  3. // Will log "prefix: /v1"
  4. request.log.info('prefix: %s', instance.prefix)
  5. reply.send({ prefix: instance.prefix })
  6. })
  7. instance.register(function (instance, opts, done) {
  8. instance.get('/bar', function (request, reply) {
  9. // Will log "prefix: /v1/v2"
  10. request.log.info('prefix: %s', instance.prefix)
  11. reply.send({ prefix: instance.prefix })
  12. })
  13. done()
  14. }, { prefix: '/v2' })
  15. done()
  16. }, { prefix: '/v1' })

pluginName

Name of the current plugin. There are three ways to define a name (in order).

  1. If you use fastify-plugin the metadata name is used.
  2. If you module.exports a plugin the filename is used.
  3. If you use a regular function declaration the function name is used.

Fallback: The first two lines of your plugin will represent the plugin name. Newlines are replaced by --. This will help to identify the root cause when you deal with many plugins.

Important: If you have to deal with nested plugins, the name differs with the usage of the fastify-plugin because no new scope is created and therefore we have no place to attach contextual data. In that case, the plugin name will represent the boot order of all involved plugins in the format of plugin-A -> plugin-B.

log

The logger instance, check here.

version

Fastify version of the instance. Used for plugin support. See Plugins for information on how the version is used by plugins.

inject

Fake HTTP injection (for testing purposes) here.

addSchema

fastify.addSchema(schemaObj), adds a JSON schema to the Fastify instance. This allows you to reuse it everywhere in your application just by using the standard $ref keyword.

To learn more, read the Validation and Serialization documentation.

getSchemas

fastify.getSchemas(), returns a hash of all schemas added via .addSchema. The keys of the hash are the $ids of the JSON Schema provided.

getSchema

fastify.getSchema(id), return the JSON schema added with .addSchema and the matching id. It returns undefined if it is not found.

setReplySerializer

Set the reply serializer for all the routes. This will be used as default if a Reply.serializer(func) has not been set. The handler is fully encapsulated, so different plugins can set different error handlers. Note: the function parameter is called only for status 2xx. Check out the setErrorHandler for errors.

  1. fastify.setReplySerializer(function (payload, statusCode){
  2. // serialize the payload with a sync function
  3. return `my serialized ${statusCode} content: ${payload}`
  4. })

setValidatorCompiler

Set the schema validator compiler for all routes. See #schema-validator.

setSchemaErrorFormatter

Set the schema error formatter for all routes. See #error-handling.

setSerializerCompiler

Set the schema serializer compiler for all routes. See #schema-serializer. Note: setReplySerializer has priority if set!

validatorCompiler

This property can be used to get the schema validator. If not set, it will be null until the server starts, then it will be a function with the signature function ({ schema, method, url, httpPart }) that returns the input schema compiled to a function for validating data. The input schema can access all the shared schemas added with .addSchema function.

serializerCompiler

This property can be used to get the schema serializer. If not set, it will be null until the server starts, then it will be a function with the signature function ({ schema, method, url, httpPart }) that returns the input schema compiled to a function for validating data. The input schema can access all the shared schemas added with .addSchema function.

schemaErrorFormatter

This property can be used to set a function to format errors that happen while the validationCompiler fails to validate the schema. See #error-handling.

schemaController

This property can be used to fully manage:

  • bucket: where the schemas of your application will be stored
  • compilersFactory: what module must compile the JSON schemas

It can be useful when your schemas are stored in another data structure that is unknown to Fastify. See issue #2446 for an example of what this property helps to resolve.

Another use case is to tweak all the schemas processing. Doing so it is possible to use Ajv v8, instead of the default v6! We will see an example of this later.

  1. const fastify = Fastify({
  2. schemaController: {
  3. /**
  4. * This factory is called whenever `fastify.register()` is called.
  5. * It may receive as input the schemas of the parent context if some schemas have been added.
  6. * @param {object} parentSchemas these schemas will be returned by the `getSchemas()` method function of the returned `bucket`.
  7. */
  8. bucket: function factory (parentSchemas) {
  9. return {
  10. addSchema (inputSchema) {
  11. // This function must store the schema added by the user.
  12. // This function is invoked when `fastify.addSchema()` is called.
  13. },
  14. getSchema (schema$id) {
  15. // This function must return the raw schema requested by the `schema$id`.
  16. // This function is invoked when `fastify.getSchema(id)` is called.
  17. return aSchema
  18. },
  19. getSchemas () {
  20. // This function must return all the schemas referenced by the routes schemas' $ref
  21. // It must return a JSON where the property is the schema `$id` and the value is the raw JSON Schema.
  22. const allTheSchemaStored = {
  23. 'schema$id1': schema1,
  24. 'schema$id2': schema2
  25. }
  26. return allTheSchemaStored
  27. }
  28. }
  29. },
  30. /**
  31. * The compilers factory let you fully control the validator and serializer
  32. * in the Fastify's lifecycle, providing the encapsulation to your compilers.
  33. */
  34. compilersFactory: {
  35. /**
  36. * This factory is called whenever a new validator instance is needed.
  37. * It may be called whenever `fastify.register()` is called only if new schemas have been added to the
  38. * encapsulation context.
  39. * It may receive as input the schemas of the parent context if some schemas have been added.
  40. * @param {object} externalSchemas these schemas will be returned by the `bucket.getSchemas()`. Needed to resolve the external references $ref.
  41. * @param {object} ajvServerOption the server `ajv` options to build your compilers accordingly
  42. */
  43. buildValidator: function factory (externalSchemas, ajvServerOption) {
  44. // This factory function must return a schema validator compiler.
  45. // See [#schema-validator](.././Validation-and-Serialization#schema-validator) for details.
  46. const yourAjvInstance = new Ajv(ajvServerOption.customOptions)
  47. return function validatorCompiler ({ schema, method, url, httpPart }) {
  48. return yourAjvInstance.compile(schema)
  49. }
  50. },
  51. /**
  52. * This factory is called whenever a new serializer instance is needed.
  53. * It may be called whenever `fastify.register()` is called only if new schemas have been added to the
  54. * encapsulation context.
  55. * It may receive as input the schemas of the parent context if some schemas have been added.
  56. * @param {object} externalSchemas these schemas will be returned by the `bucket.getSchemas()`. Needed to resolve the external references $ref.
  57. * @param {object} serializerOptsServerOption the server `serializerOpts` options to build your compilers accordingly
  58. */
  59. buildSerializer: function factory (externalSchemas, serializerOptsServerOption) {
  60. // This factory function must return a schema serializer compiler.
  61. // See [#schema-serializer](.././Validation-and-Serialization#schema-serializer) for details.
  62. return function serializerCompiler ({ schema, method, url, httpStatus }) {
  63. return data => JSON.stringify(data)
  64. }
  65. }
  66. }
  67. }
  68. });
Ajv 8 as default schema validator

Ajv 8 is the evolution of Ajv 6, and it has a lot of improvements and new features. To use the new Ajv 8 features such as JTD or the Standalone mode, refer to the @fastify/ajv-compiler documentation.

To use Ajv 8 as default schema validator, you can use the following code:

  1. const AjvCompiler = require('@fastify/ajv-compiler') // It must be the v2.x.x version
  2. // Note that the `format` schema's keyword is no longer supported on Ajv 8 by default.
  3. // So you need to add it manually.
  4. const ajvFormats = require('ajv-formats')
  5. const app = fastify({
  6. ajv: {
  7. customOptions: {
  8. validateFormats: true
  9. },
  10. plugins: [ajvFormats]
  11. },
  12. schemaController: {
  13. compilersFactory: {
  14. buildValidator: AjvCompiler()
  15. }
  16. }
  17. })
  18. // Done! You can now use Ajv 8 options and keywords in your schemas!

setNotFoundHandler

fastify.setNotFoundHandler(handler(request, reply)): set the 404 handler. This call is encapsulated by prefix, so different plugins can set different not found handlers if a different prefix option is passed to fastify.register(). The handler is treated as a regular route handler so requests will go through the full Fastify lifecycle.

You can also register preValidation and preHandler hooks for the 404 handler.

Note: The preValidation hook registered using this method will run for a route that Fastify does not recognize and not when a route handler manually calls reply.callNotFound. In which case, only preHandler will be run.

  1. fastify.setNotFoundHandler({
  2. preValidation: (req, reply, done) => {
  3. // your code
  4. done()
  5. },
  6. preHandler: (req, reply, done) => {
  7. // your code
  8. done()
  9. }
  10. }, function (request, reply) {
  11. // Default not found handler with preValidation and preHandler hooks
  12. })
  13. fastify.register(function (instance, options, done) {
  14. instance.setNotFoundHandler(function (request, reply) {
  15. // Handle not found request without preValidation and preHandler hooks
  16. // to URLs that begin with '/v1'
  17. })
  18. done()
  19. }, { prefix: '/v1' })

Fastify calls setNotFoundHandler to add a default 404 handler at startup before plugins are registered. If you would like to augment the behavior of the default 404 handler, for example with plugins, you can call setNotFoundHandler with no arguments fastify.setNotFoundHandler() within the context of these registered plugins.

setErrorHandler

fastify.setErrorHandler(handler(error, request, reply)): Set a function that will be called whenever an error happens. The handler is bound to the Fastify instance and is fully encapsulated, so different plugins can set different error handlers. async-await is supported as well.

Note: If the error statusCode is less than 400, Fastify will automatically set it at 500 before calling the error handler.

  1. fastify.setErrorHandler(function (error, request, reply) {
  2. // Log error
  3. this.log.error(error)
  4. // Send error response
  5. reply.status(409).send({ ok: false })
  6. })

Fastify is provided with a default function that is called if no error handler is set. It can be accessed using fastify.errorHandler and it logs the error with respect to its statusCode.

  1. var statusCode = error.statusCode
  2. if (statusCode >= 500) {
  3. log.error(error)
  4. } else if (statusCode >= 400) {
  5. log.info(error)
  6. } else {
  7. log.error(error)
  8. }

printRoutes

fastify.printRoutes(): Prints the representation of the internal radix tree used by the router, useful for debugging. Alternatively, fastify.printRoutes({ commonPrefix: false }) can be used to print the flattened routes tree.

Remember to call it inside or after a ready call.

  1. fastify.get('/test', () => {})
  2. fastify.get('/test/hello', () => {})
  3. fastify.get('/hello/world', () => {})
  4. fastify.get('/helicopter', () => {})
  5. fastify.ready(() => {
  6. console.log(fastify.printRoutes())
  7. // └── /
  8. // ├── test (GET)
  9. // │ └── /hello (GET)
  10. // └── hel
  11. // ├── lo/world (GET)
  12. // └── licopter (GET)
  13. console.log(fastify.printRoutes({ commonPrefix: false }))
  14. // └── / (-)
  15. // ├── test (GET)
  16. // │ └── /hello (GET)
  17. // ├── hello/world (GET)
  18. // └── helicopter (GET)
  19. })

fastify.printRoutes({ includeMeta: (true | []) }) will display properties from the route.store object for each displayed route. This can be an array of keys (e.g. ['onRequest', Symbol('key')]), or true to display all properties. A shorthand option, fastify.printRoutes({ includeHooks: true }) will include all hooks.

  1. console.log(fastify.printRoutes({ includeHooks: true, includeMeta: ['metaProperty'] }))
  2. // └── /
  3. // ├── test (GET)
  4. // │ • (onRequest) ["anonymous()","namedFunction()"]
  5. // │ • (metaProperty) "value"
  6. // │ └── /hello (GET)
  7. // └── hel
  8. // ├── lo/world (GET)
  9. // │ • (onTimeout) ["anonymous()"]
  10. // └── licopter (GET)
  11. console.log(fastify.printRoutes({ includeHooks: true }))
  12. // └── /
  13. // ├── test (GET)
  14. // │ • (onRequest) ["anonymous()","namedFunction()"]
  15. // │ └── /hello (GET)
  16. // └── hel
  17. // ├── lo/world (GET)
  18. // │ • (onTimeout) ["anonymous()"]
  19. // └── licopter (GET)

printPlugins

fastify.printPlugins(): Prints the representation of the internal plugin tree used by the avvio, useful for debugging require order issues.

Remember to call it inside or after a ready call.

  1. fastify.register(async function foo (instance) {
  2. instance.register(async function bar () {})
  3. })
  4. fastify.register(async function baz () {})
  5. fastify.ready(() => {
  6. console.error(fastify.printPlugins())
  7. // will output the following to stderr:
  8. // └── root
  9. // ├── foo
  10. // │ └── bar
  11. // └── baz
  12. })

addContentTypeParser

fastify.addContentTypeParser(content-type, options, parser) is used to pass custom parser for a given content type. Useful for adding parsers for custom content types, e.g. text/json, application/vnd.oasis.opendocument.text. content-type can be a string, string array or RegExp.

  1. // The two arguments passed to getDefaultJsonParser are for ProtoType poisoning and Constructor Poisoning configuration respectively. The possible values are 'ignore', 'remove', 'error'. ignore skips all validations and it is similar to calling JSON.parse() directly. See the [`secure-json-parse` documentation](https://github.com/fastify/secure-json-parse#api) for more information.
  2. fastify.addContentTypeParser('text/json', { asString: true }, fastify.getDefaultJsonParser('ignore', 'ignore'))

getDefaultJsonParser

fastify.getDefaultJsonParser(onProtoPoisoning, onConstructorPoisoning) takes two arguments. First argument is ProtoType poisoning configuration and second argument is constructor poisoning configuration. See the secure-json-parse documentation for more information.

defaultTextParser

fastify.defaultTextParser() can be used to parse content as plain text.

  1. fastify.addContentTypeParser('text/json', { asString: true }, fastify.defaultTextParser())

errorHandler

fastify.errorHandler can be used to handle errors using fastify’s default error handler.

  1. fastify.get('/', {
  2. errorHandler: (error, request, reply) => {
  3. if (error.code === 'SOMETHING_SPECIFIC') {
  4. reply.send({ custom: 'response' })
  5. return
  6. }
  7. fastify.errorHandler(error, request, response)
  8. }
  9. }, handler)

initialConfig

fastify.initialConfig: Exposes a frozen read-only object registering the initial options passed down by the user to the Fastify instance.

Currently the properties that can be exposed are:

  • connectionTimeout
  • keepAliveTimeout
  • bodyLimit
  • caseSensitive
  • http2
  • https (it will return false/true or { allowHTTP1: true/false } if explicitly passed)
  • ignoreTrailingSlash
  • disableRequestLogging
  • maxParamLength
  • onProtoPoisoning
  • onConstructorPoisoning
  • pluginTimeout
  • requestIdHeader
  • requestIdLogLabel
  • http2SessionTimeout
  1. const { readFileSync } = require('fs')
  2. const Fastify = require('fastify')
  3. const fastify = Fastify({
  4. https: {
  5. allowHTTP1: true,
  6. key: readFileSync('./fastify.key'),
  7. cert: readFileSync('./fastify.cert')
  8. },
  9. logger: { level: 'trace'},
  10. ignoreTrailingSlash: true,
  11. maxParamLength: 200,
  12. caseSensitive: true,
  13. trustProxy: '127.0.0.1,192.168.1.1/24',
  14. })
  15. console.log(fastify.initialConfig)
  16. /*
  17. will log :
  18. {
  19. caseSensitive: true,
  20. https: { allowHTTP1: true },
  21. ignoreTrailingSlash: true,
  22. maxParamLength: 200
  23. }
  24. */
  25. fastify.register(async (instance, opts) => {
  26. instance.get('/', async (request, reply) => {
  27. return instance.initialConfig
  28. /*
  29. will return :
  30. {
  31. caseSensitive: true,
  32. https: { allowHTTP1: true },
  33. ignoreTrailingSlash: true,
  34. maxParamLength: 200
  35. }
  36. */
  37. })
  38. instance.get('/error', async (request, reply) => {
  39. // will throw an error because initialConfig is read-only
  40. // and can not be modified
  41. instance.initialConfig.https.allowHTTP1 = false
  42. return instance.initialConfig
  43. })
  44. })
  45. // Start listening.
  46. fastify.listen(3000, (err) => {
  47. if (err) {
  48. fastify.log.error(err)
  49. process.exit(1)
  50. }
  51. })