Documentation
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
.
fastify
.register((instance, opts, next) => {
console.log('Current plugin')
next()
})
.after(err => {
console.log('After current plugin')
})
.register((instance, opts, next) => {
console.log('Next plugin')
next()
})
.ready(err => {
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.
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)
})
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.
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)
}
})
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)
})
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)
}
})
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.
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.
basepath
The full path that will be prefixed to a route.
Example:
fastify.register(function (instance, opts, next) {
instance.get('/foo', function (request, reply) {
// Will log "basePath: /v1"
request.log.info('basePath: %s', instance.basePath)
reply.send({basePath: instance.basePath})
})
instance.register(function (instance, opts, next) {
instance.get('/bar', function (request, reply) {
// Will log "basePath: /v1/v2"
request.log.info('basePath: %s', instance.basePath)
reply.send({basePath: instance.basePath})
})
next()
}, { prefix: '/v2' })
next()
}, { 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.
setSchemaCompiler
Set the schema compiler for all routes here.
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 beforeHandler hook for the 404 handler.
fastify.setNotFoundHandler({
beforeHandler: (req, reply, next) => {
req.body.beforeHandler = true
next()
}
}, function (request, reply) {
// Default not found handler with beforeHandler hook
})
fastify.register(function (instance, options, next) {
instance.setNotFoundHandler(function (request, reply) {
// Handle not found request without beforeHandler hook
// to URLs that begin with '/v1'
})
next()
}, { 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.
fastify.setErrorHandler(function (error, request, reply) {
// Send error response
})
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.
fastify.get('/test', () => {})
fastify.get('/test/hello', () => {})
fastify.get('/hello/world', () => {})
fastify.ready(() => {
console.log(fastify.printRoutes())
// └── /
// ├── test (GET)
// │ └── /hello (GET)
// └── hello/world (GET)
})