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.
If true
Node.js core's HTTP/2 module is used for binding the socket.
- Default:
false
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
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)
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)
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
const fastify = require('fastify')({
ignoreTrailingSlash: true
})
// registers both "/foo" and "/foo/"
fastify.get('/foo/', function (req, reply) {
reply.send('foo')
})
// registers both "/bar" and "/bar/"
fastify.get('/bar', function (req, reply) {
reply.send('bar')
})
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.
Defines the maximum payload, in bytes, the server is allowed to accept.
- Default:
1048576
(1MiB)
Defines what action the framework must take when parsing a JSON object
with __proto__
. This functionality is provided by
secure-json-parse.
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'
Defines what action the framework must take when parsing a JSON object
with constructor
. This functionality is provided by
secure-json-parse.
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:
'ignore'
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 forreq
(incoming request objects),res
(outgoing response objets), anderr
(standardError
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:Any user supplied serializer will override the default serializer of the corresponding property.fastify.get('/foo', function (req, res) { req.log.info({req}) // log the serialized request object res.send('foo') })
-
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:const pino = require('pino')(); const customLogger = { info: function (o, ...n) {}, warn: function (o, ...n) {}, error: function (o, ...n) {}, fatal: function (o, ...n) {}, trace: function (o, ...n) {}, debug: function (o, ...n) {}, child: function() { const child = Object.create(this); child.pino = pino.child(...arguments); return child; }, }; const fastify = require('fastify')({logger: customLogger});
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
// Examples of hooks to replicate the disabled functionality.
fastify.addHook('onRequest', (req, reply, done) => {
req.log.info({ url: req.raw.url, id: req.id }, 'received request')
done()
})
fastify.addHook('onResponse', (req, reply, done) => {
req.log.info({ url: req.raw.originalUrl, statusCode: reply.raw.statusCode }, 'request completed')
done()
})
Please note that this setting will also disable an error log written by the the default onResponse
hook on reply callback errors.
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.
const serverFactory = (handler, opts) => {
const server = http.createServer((req, res) => {
handler(req, res)
})
return server
}
const fastify = Fastify({ serverFactory })
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
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.
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.
fastify.get('/user/:username', (request, reply) => {
// Given the URL: /USER/NodeJS
console.log(request.params.username) // -> 'NodeJS'
})
Please note this setting this option to false
goes against
RFC3986.
The header name used to know the request id. See the request id section.
- Default:
'request-id'
Defines the label used for the request identifier when logging the request.
- Default:
'reqId'
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 behaviour as shown below. For generating UUID
s you may want to checkout hyperid
let i = 0
const fastify = require('fastify')({
genReqId: function (req) { return i++ }
})
Note: genReqId will not be called if the header set in requestIdHeader
is available (defaults to 'request-id').
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.
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 takesaddress
as first argfunction myTrustFn(address, hop) { return address === '1.2.3.4' || hop === 1 }
For more examples refer to proxy-addr package.
You may access the ip
, ips
, hostname
and protocol
values on the request
object.
fastify.get('/', (request, reply) => {
console.log(request.ip)
console.log(request.ips)
console.log(request.hostname)
console.log(request.protocol)
})
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
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
.
const qs = require('qs')
const fastify = require('fastify')({
querystringParser: str => qs.parse(str)
})
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.
const versioning = {
storage: function () {
let versions = {}
return {
get: (version) => { return versions[version] || null },
set: (version, store) => { versions[version] = store },
del: (version) => { delete versions[version] },
empty: () => { versions = {} }
}
},
deriveVersion: (req, ctx) => {
return req.headers['accept']
}
}
const fastify = require('fastify')({
versioning
})
Returns 503 after calling close
server method.
If false
, the server routes the incoming request as usual.
- Default:
true
Configure the ajv instance used by Fastify without providing a custom one.
- Default:
{
customOptions: {
removeAdditional: true,
useDefaults: true,
coerceTypes: true,
allErrors: false,
nullable: true
},
plugins: []
}
const fastify = require('fastify')({
ajv: {
customOptions: {
nullable: false // Refer to [ajv options](https://ajv.js.org/#options)
},
plugins: [
require('ajv-merge-patch')
[require('ajv-keywords'), 'instanceof'];
// Usage: [plugin, pluginOptions] - Plugin with options
// Usage: plugin - Plugin without options
]
}
})
Set a default
timeout to every incoming http2 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 http2. Node core defaults this to 0
.
- Default:
null
Fastify provides default error handlers for the most common use cases. Using this option it is possible to override one or more of those handlers with custom code.
Note: Only FST_ERR_BAD_URL
is implemented at the moment.
const fastify = require('fastify')({
frameworkErrors: function (error, req, res) {
if (error instanceof FST_ERR_BAD_URL) {
res.code(400)
return res.send("Provided url is not valid")
} else {
res.send(err)
}
}
})
Set a clientErrorHandler that listens to error
events emitted by client connections and responds with a 400
.
Using this option it is possible to override the default clientErrorHandler
.
- Default:
function defaultClientErrorHandler (err, socket) {
if (err.code === 'ECONNRESET') {
return
}
const body = JSON.stringify({
error: http.STATUS_CODES['400'],
message: 'Client Error',
statusCode: 400
})
this.log.trace({ err }, 'client error')
if (socket.writable) {
socket.end(`HTTP/1.1 400 Bad Request\r\nContent-Length: ${body.length}\r\nContent-Type: application/json\r\n\r\n${body}`)
}
}
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 it's still writable as it may already have been destroyed.
const fastify = require('fastify')({
clientErrorHandler: function (err, socket) {
const body = JSON.stringify({
error: {
message: 'Client error',
code: '400'
}
})
// `this` is bound to fastify instance
this.log.trace({ err }, 'client error')
// the handler is responsible for generating a valid HTTP response
socket.end(`HTTP/1.1 400 Bad Request\r\nContent-Length: ${body.length}\r\nContent-Type: application/json\r\n\r\n${body}`)
}
})
Set a sync callback function that must return a string that allows rewriting urls.
Rewriting a url will modify the
url
property of thereq
object
function rewriteUrl (req) { // req is the Node.js HTTP request
return req.url === '/hi' ? '/hello' : req.url;
}
Note that rewriteUrl
is called before routing, it is not encapsulated and it is an instance-wide configuration.
fastify.server
: The Node core server object as returned by the Fastify factory function
.
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
.
fastify
.register((instance, opts, done) => {
console.log('Current plugin')
done()
})
.after(err => {
console.log('After current plugin')
})
.register((instance, opts, done) => {
console.log('Next plugin')
done()
})
.ready(err => {
console.log('Everything has been loaded')
})
In case after()
is called without a function, it returns a Promise
:
fastify.register(async (instance, opts) => {
console.log('Current plugin')
})
await fastify.after()
console.log('After current plugin')
fastify.register(async (instance, opts) => {
console.log('Next plugin')
})
await fastify.ready()
console.log('Everything has been loaded')
Function called when all the plugins have been loaded. It takes an error parameter if something went wrong.
fastify.ready(err => {
if (err) throw err
})
If it is called without any arguments, it will return a Promise
:
fastify.ready().then(() => {
console.log('successfully booted!')
}, (err) => {
console.log('an error happened', err)
})
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.
fastify.listen(3000, (err, address) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
Specifying an address is also supported:
fastify.listen(3000, '127.0.0.1', (err, address) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
Specifying a backlog queue size is also supported:
fastify.listen(3000, '127.0.0.1', 511, (err, address) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
Specifying options is also supported, the object is same as options in the Node.js server listen:
fastify.listen({ port: 3000, host: '127.0.0.1', backlog: 511 }, (err) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
If no callback is provided a Promise is returned:
fastify.listen(3000)
.then((address) => console.log(`server listening on ${address}`))
.catch(err => {
console.log('Error starting server:', err)
process.exit(1)
})
Specifying an address without a callback is also supported:
fastify.listen(3000, '127.0.0.1')
.then((address) => console.log(`server listening on ${address}`))
.catch(err => {
console.log('Error starting server:', err)
process.exit(1)
})
Specifying options without a callback is also supported:
fastify.listen({ port: 3000, host: '127.0.0.1', backlog: 511 })
.then((address) => console.log(`server listening on ${address}`))
.catch(err => {
console.log('Error starting server:', err)
process.exit(1)
})
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
:
fastify.listen(3000, '0.0.0.0', (err, address) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
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:
fastify.listen({
port: 0,
host: 'localhost',
exclusive: false,
readableAll: false,
writableAll: false,
ipv6Only: false
}, (err) => {})
Method to add routes to the server, it also has shorthand functions, check here.
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 behaviour.
If it is called without any arguments, it will return a Promise:
fastify.close().then(() => {
console.log('successfully closed!')
}, (err) => {
console.log('an error happened', err)
})
Function useful if you need to decorate the fastify instance, Reply or Request, check here.
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.
Function to add a specific hook in the lifecycle of Fastify, check here.
The full path that will be prefixed to a route.
Example:
fastify.register(function (instance, opts, done) {
instance.get('/foo', function (request, reply) {
// Will log "prefix: /v1"
request.log.info('prefix: %s', instance.prefix)
reply.send({ prefix: instance.prefix })
})
instance.register(function (instance, opts, done) {
instance.get('/bar', function (request, reply) {
// Will log "prefix: /v1/v2"
request.log.info('prefix: %s', instance.prefix)
reply.send({ prefix: instance.prefix })
})
done()
}, { prefix: '/v2' })
done()
}, { prefix: '/v1' })
Name of the current plugin. There are three ways to define a name (in order).
- If you use fastify-plugin the metadata
name
is used. - If you
module.exports
a plugin the filename is used. - 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 indentify 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
.
The logger instance, check here.
Fastify version of the instance. Used for plugin support. See Plugins for information on how the version is used by plugins.
Fake http injection (for testing purposes) here.
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.
fastify.getSchemas()
, returns a hash of all schemas added via .addSchema
. The keys of the hash are the $id
s of the JSON Schema provided.
fastify.getSchema(id)
, return the JSON schema added with .addSchema
and the matching id
. It returns undefined
if it is not found.
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.
fastify.setReplySerializer(function (payload, statusCode){
// serialize the payload with a sync function
return `my serialized ${statusCode} content: ${payload}`
})
Set the schema validator compiler for all routes. See #schema-validator.
Set the schema error formatter for all routes. See #error-handling.
Set the schema serializer compiler for all routes. See #schema-serializer.
Note: setReplySerializer
has priority if set!
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.
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.
This property can be used to format errors that happen while the validationCompiler
fails to validate the schema. See #error-handling.
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 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.
fastify.setNotFoundHandler({
preValidation: (req, reply, done) => {
// your code
done()
},
preHandler: (req, reply, done) => {
// your code
done()
}
}, function (request, reply) {
// Default not found handler with preValidation and preHandler hooks
})
fastify.register(function (instance, options, done) {
instance.setNotFoundHandler(function (request, reply) {
// Handle not found request without preValidation and preHandler hooks
// to URLs that begin with '/v1'
})
done()
}, { prefix: '/v1' })
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.
fastify.setErrorHandler(function (error, request, reply) {
// Log error
// Send error response
})
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
:
var statusCode = error.statusCode
if (statusCode >= 500) {
log.error(error)
} else if (statusCode >= 400) {
log.info(error)
} else {
log.error(error)
}
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.
fastify.get('/test', () => {})
fastify.get('/test/hello', () => {})
fastify.get('/hello/world', () => {})
fastify.ready(() => {
console.log(fastify.printRoutes())
// └── /
// ├── test (GET)
// │ └── /hello (GET)
// └── hello/world (GET)
})
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
- maxParamLength
- onProtoPoisoning
- pluginTimeout
- requestIdHeader
const { readFileSync } = require('fs')
const Fastify = require('fastify')
const fastify = Fastify({
https: {
allowHTTP1: true,
key: readFileSync('./fastify.key'),
cert: readFileSync('./fastify.cert')
},
logger: { level: 'trace'},
ignoreTrailingSlash: true,
maxParamLength: 200,
caseSensitive: true,
trustProxy: '127.0.0.1,192.168.1.1/24',
})
console.log(fastify.initialConfig)
/*
will log :
{
caseSensitive: true,
https: { allowHTTP1: true },
ignoreTrailingSlash: true,
maxParamLength: 200
}
*/
fastify.register(async (instance, opts) => {
instance.get('/', async (request, reply) => {
return instance.initialConfig
/*
will return :
{
caseSensitive: true,
https: { allowHTTP1: true },
ignoreTrailingSlash: true,
maxParamLength: 200
}
*/
})
instance.get('/error', async (request, reply) => {
// will throw an error because initialConfig is read-only
// and can not be modified
instance.initialConfig.https.allowHTTP1 = false
return instance.initialConfig
})
})
// Start listening.
fastify.listen(3000, (err) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})