Documentation

Server Methods

server

fastify.server: The Node core server object

ready

Function called when all the plugins has 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.

fastify.listen(3000, err => {
  if (err) throw err
})

Specifying an address is also supported:

fastify.listen(3000, '127.0.0.1', err => {
  if (err) throw err
})

If no callback is provided a Promise is returned:

fastify.listen(3000)
  .then(() => console.log('Listening'))
  .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(() => console.log('Listening'))
  .catch(err => {
    console.log('Error starting server:', err)
    process.exit(1)
  })

route

Method to add routes to the server, it also have shorthands functions, check here.

routes iterator

The Fastify instance is an Iterable object with all the registered routes. The route properties are the same the developer has declared here.

fastify.get('/route', opts, handler)

fastify.ready(() => {
  for (var route of fastify) {
    console.log(route)
    /* will output:
    {
      '/route': {
        get: {
          method: String,
          url: String,
          schema: Object,
          handler: Function,
          Request: Function,
          Reply: Function
        }
      }
    }
    */
  }
})

close

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

decorate*

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

register

Fastify allows the user to extend its functionalities 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.

log

The logger instance, check here.

inject

Fake http injection (for testing purposes) here.

setSchemaCompiler

Set the schema compiler for all routes here.

setNotFoundHandler

fastify.setNotFoundHandler(handler(request, reply)): set the 404 handler. This call is fully encapsulated, so different plugins can set different not found handlers.

setErrorHandler

fastify.setErrorHandler(handler(error, 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.