Server
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.
- Factory
http2
https
connectionTimeout
keepAliveTimeout
forceCloseConnections
maxRequestsPerSocket
requestTimeout
ignoreTrailingSlash
ignoreDuplicateSlashes
maxParamLength
bodyLimit
onProtoPoisoning
onConstructorPoisoning
logger
disableRequestLogging
serverFactory
jsonShorthand
caseSensitive
allowUnsafeRegex
requestIdHeader
requestIdLogLabel
genReqId
trustProxy
pluginTimeout
querystringParser
exposeHeadRoutes
constraints
return503OnClosing
ajv
serializerOpts
http2SessionTimeout
frameworkErrors
clientErrorHandler
rewriteUrl
- Instance
- Server Methods
- server
- after
- ready
- listen
- addresses
- getDefaultRoute
- setDefaultRoute
- routing
- route
- hasRoute
- close
- decorate*
- register
- addHook
- prefix
- pluginName
- hasPlugin
- log
- version
- inject
- addSchema
- getSchemas
- getSchema
- setReplySerializer
- setValidatorCompiler
- setSchemaErrorFormatter
- setSerializerCompiler
- validatorCompiler
- serializerCompiler
- schemaErrorFormatter
- schemaController
- setNotFoundHandler
- setErrorHandler
- addConstraintStrategy
- hasConstraintStrategy
- printRoutes
- printPlugins
- addContentTypeParser
- hasContentTypeParser
- removeContentTypeParser
- removeAllContentTypeParsers
- getDefaultJsonParser
- defaultTextParser
- errorHandler
- initialConfig
- Server Methods
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:
72000
(72 seconds)
forceCloseConnections
When set to true
, upon close
the server will iterate the current
persistent connections and destroy their
sockets.
Important: connections are not inspected to determine if requests have been completed.
Fastify will prefer the HTTP server's
closeAllConnections
method if supported, otherwise it will use internal connection tracking.
When set to "idle"
, upon close
the server will iterate the current
persistent connections which are not sending a request or waiting for a response
and destroy their sockets. The value is supported only if the HTTP server
supports the
closeIdleConnections
method, otherwise attempting to set it will throw an exception.
- Default:
"idle"
if the HTTP server allows it,false
otherwise
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. By default, Fastify is set to take into account the trailing slashes.
Paths like /foo
and /foo/
will be treated as different paths. If you want to
change this, set this flag to true
. That way, both /foo
and /foo/
will
point to the same route. 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')
})
ignoreDuplicateSlashes
Fastify uses find-my-way to handle
routing. You can use ignoreDuplicateSlashes
option to remove duplicate slashes
from the path. It removes duplicate slashes in the route path and in the request
URL. This option applies to all route registrations for the resulting server
instance.
Note that when ignoreTrailingSlash
and ignoreDuplicateSlashes
are both set
to true, Fastify will remove duplicate slashes, and then trailing slashes,
meaning //a//b//c// will be converted to /a/b/c.
- Default:
false
const fastify = require('fastify')({
ignoreDuplicateSlashes: true
})
// registers "/foo/bar/"
fastify.get('///foo//bar//', function (req, reply) {
reply.send('foo')
})
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 a 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 forreq
(incoming request objects),res
(outgoing response objects), 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});
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
// 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
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.
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({ port: 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.
const AjvJTD = require('ajv/dist/jtd'/* only valid for AJV v7+ */)
const ajv = new AjvJTD({
// This would let you throw at start for invalid JTD schema objects
allErrors: process.env.NODE_ENV === 'development'
})
const fastify = Fastify({ jsonShorthand: false })
fastify.setValidatorCompiler(({ schema }) => {
return ajv.compile(schema)
})
fastify.post('/', {
schema: {
body: {
properties: {
foo: { type: 'uint8' }
}
}
},
handler (req, reply) { reply.send({ ok: 1 }) }
})
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.
fastify.get('/user/:username', (request, reply) => {
// Given the URL: /USER/NodeJS
console.log(request.params.username) // -> 'NodeJS'
})
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
.
allowUnsafeRegex
The allowUnsafeRegex setting is false by default, so routes only allow safe regular expressions. To use unsafe expressions, set allowUnsafeRegex to true.
fastify.get('/user/:id(^([0-9]+){4}$)', (request, reply) => {
// Throws an error without allowUnsafeRegex = true
})
Under the hood: FindMyWay More info about safe regexp: Safe-regex2
requestIdHeader
The header name used to set the request-id. See the
request-id section.
Setting requestIdHeader
to false
will always use genReqId
- Default:
'request-id'
const fastify = require('fastify')({
requestIdHeader: 'x-custom-id', // -> use 'X-Custom-Id' header if available
//requestIdHeader: false, // -> always use genReqId
})
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. This function is expected to be error-free.
- 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 UUID
s you may want to check
out 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').
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.
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 the
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)
})
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