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

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 bourne. See https://hueniverse.com/a-tale-of-prototype-poisoning-2610fa170061 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:

    • genReqId: a synchronous function that will be used to generate identifiers for incoming requests. The default function generates sequential identifiers.
    • 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 repsonse objets), 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, next) => {
  3. req.log.info({ url: req.req.url, id: req.id }, 'received request')
  4. next()
  5. })
  6. fastify.addHook('onResponse', (req, reply, next) => {
  7. req.log.info({ url: req.req.originalUrl, statusCode: res.res.statusCode }, 'request completed')
  8. next()
  9. })

serverFactory

You can pass a custom http server to Fastify by using the serverFactory option.serverFactory is a function that takes an 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, modifyCoreObjects: false })
  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.Note that we have also added modifyCoreObjects: false because in some serverless environments such as Google Cloud Functions, some Node.js core properties are not writable.

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 this setting this option to false goes against RFC3986.

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' if provided or monotonically increasing integersEspecially in distributed systems, you may want to override the default id generation behaviour as shown below. For generating UUIDs you may want to checkout hyperid
  1. let i = 0
  2. const fastify = require('fastify')({
  3. genReqId: function (req) { return req.headers['request-id'] || i++ }
  4. })

Note: genReqId will not be called if the 'request-id' header is available.

trustProxy

By enabling the trustProxy option, Fastify will have knowledge that it's 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 proxy-addr package.

You may access the ip, ips, and hostname 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. })

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. })

versioning

By default you can version your routes with semver versioning, which is provided by find-my-way. There is still an option to provide custom versioning strategy. You can find more information in the find-my-way documentation.

  1. const versioning = {
  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. versioning
  17. })

modifyCoreObjects

  • Default: trueBy default, Fastify will add the ip, ips, hostname, and log properties to Node's raw request object (see Request) and the log property to Node's raw response object. Set to false to prevent these properties from being added to the Node core objects.
  1. const fastify = Fastify({ modifyCoreObjects: true }) // the default
  2. fastify.get('/', (request, reply) => {
  3. console.log(request.raw.ip)
  4. console.log(request.raw.ips)
  5. console.log(request.raw.hostname)
  6. request.raw.log('Hello')
  7. reply.res.log('World')
  8. })

Disable this option could help in serverless environments such as Google Cloud Functions, where ip and ips are not writable properties.

Note that these properties are deprecated and will be removed in the next major version of Fastify along with this option. It is recommended to use the same properties on Fastify's Request and Reply objects instead.

  1. const fastify = Fastify({ modifyCoreObjects: false })
  2. fastify.get('/', (request, reply) => {
  3. console.log(request.ip)
  4. console.log(request.ips)
  5. console.log(request.hostname)
  6. request.log('Hello')
  7. reply.log('World')
  8. })

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, next) => {
  3. console.log('Current plugin')
  4. next()
  5. })
  6. .after(err => {
  7. console.log('After current plugin')
  8. })
  9. .register((instance, opts, next) => {
  10. console.log('Next plugin')
  11. next()
  12. })
  13. .ready(err => {
  14. console.log('Everything has been loaded')
  15. })

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 address. 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) => {})

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.

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.

use

Function to add middlewares to Fastify, 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, next) {
  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, next) {
  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. next()
  14. }, { prefix: '/v2' })
  15. next()
  16. }, { prefix: '/v1' })

log

The logger instance, check here.

inject

Fake http injection (for testing purposes) here.

addSchema

fastify.addSchema(schemaObj), adds a shared schema to the Fastify instance. This allows you to reuse it everywhere in your application just by writing the schema id that you need.To learn more, see shared schema example in the Validation and Serialization documentation.

setReplySerializer

Set the reply serializer for all the routes. This will 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. Checkout 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. })

setSchemaCompiler

Set the schema compiler for all routes here.

schemaCompiler

This property can be used to set the schema compiler, it is a shortcut for the setSchemaCompiler method, and get the schema compiler back for all routes.

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 like a regular route handler so requests will go through the full Fastify lifecycle.

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

  1. fastify.setNotFoundHandler({
  2. preValidation: (req, reply, next) => {
  3. // your code
  4. next()
  5. },
  6. preHandler: (req, reply, next) => {
  7. // your code
  8. next()
  9. }
  10. }, function (request, reply) {
  11. // Default not found handler with preValidation and preHandler hooks
  12. })
  13. fastify.register(function (instance, options, next) {
  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. next()
  19. }, { prefix: '/v1' })

setErrorHandler

fastify.setErrorHandler(handler(error, request, reply)): Set a function that will be called whenever an error happens. The handler 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. // Send error response
  4. })

Fastify is provided with a default function that is called if no error handler is set and that 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.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.ready(() => {
  5. console.log(fastify.printRoutes())
  6. // └── /
  7. // ├── test (GET)
  8. // │ └── /hello (GET)
  9. // └── hello/world (GET)
  10. })

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:

  • bodyLimit
  • caseSensitive
  • http2
  • https (it will return false/true or { allowHTTP1: true/false } if explicitly passed)
  • ignoreTrailingSlash
  • maxParamLength
  • onProtoPoisoning
  • pluginTimeout
  • requestIdHeader
  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. })