Getting Started

Hello! Thank you for checking out Fastify!This document aims to be a gentle introduction to the framework and its features. It is an elementary introduction with examples and links to other parts of the documentation.Let's start!

Install

Install with npm:

  1. npm i fastify --save

Install with yarn:

  1. yarn add fastify

Your first server

Let's write our first server:

  1. // Require the framework and instantiate it
  2. const fastify = require('fastify')({
  3. logger: true
  4. })
  5. // Declare a route
  6. fastify.get('/', function (request, reply) {
  7. reply.send({ hello: 'world' })
  8. })
  9. // Run the server!
  10. fastify.listen(3000, function (err, address) {
  11. if (err) {
  12. fastify.log.error(err)
  13. process.exit(1)
  14. }
  15. fastify.log.info(`server listening on ${address}`)
  16. })

Do you prefer to use async/await? Fastify supports it out-of-the-box.(we also suggest using make-promises-safe to avoid file descriptor and memory leaks)

  1. const fastify = require('fastify')()
  2. fastify.get('/', async (request, reply) => {
  3. return { hello: 'world' }
  4. })
  5. const start = async () => {
  6. try {
  7. await fastify.listen(3000)
  8. } catch (err) {
  9. fastify.log.error(err)
  10. process.exit(1)
  11. }
  12. }
  13. start()

Awesome, that was easy.Unfortunately, writing a complex application requires significantly more code than this example. A classic problem when you are building a new application is how handle multiple files, asynchronous bootstrapping and the architecture of your code.Fastify offers an easy platform that helps solve all of problems, and more.

Note

The above examples, and subsequent examples in this document, default to listening only on the localhost 127.0.0.1 interface. To listen on all available IPv4 interfaces the example should be modified to listen on 0.0.0.0 like so:

  1. fastify.listen(3000, '0.0.0.0', function (err, address) { if (err) { fastify.log.error(err) process.exit(1) } fastify.log.info(server listening on ${address})})

Similarly, specify ::1 to accept only local connections via IPv6. Or specify :: to accept connections on all IPv6 addresses, and, if the operating system supports it, also on all IPv4 addresses.

When deploying to a Docker, or other type of, container this would be the easiest method for exposing the application.

Your first plugin

As with JavaScript everything is an object, with Fastify everything is a plugin.Before digging into it, let's see how it works!Let's declare our basic server, but instead of declaring the route inside the entry point, we'll declare it in an external file (checkout the route declaration docs).

  1. const fastify = require('fastify')({
  2. logger: true
  3. })
  4. fastify.register(require('./our-first-route'))
  5. fastify.listen(3000, function (err, address) {
  6. if (err) {
  7. fastify.log.error(err)
  8. process.exit(1)
  9. }
  10. fastify.log.info(`server listening on ${address}`)
  11. })
  1. // our-first-route.js
  2. async function routes (fastify, options) {
  3. fastify.get('/', async (request, reply) => {
  4. return { hello: 'world' }
  5. })
  6. }
  7. module.exports = routes

In this example we used the register API. This API is the core of the Fastify framework, and is the only way to register routes, plugins and so on.

At the beginning of this guide we noted that Fastify provides a foundation that assists with the asynchronous bootstrapping of your application. Why this is important? Consider the scenario where a database connection is needed to handle data storage. Obviously the database connection needs to be available prior to the server accepting connections. How do we address this problem?A typical solution is to use a complex callback, or promises, system that will mix the framework API with other libraries and the application code.Fastify handles this internally, with minimum effort!

Let's rewrite the above example with a database connection.(we will use a simple example, for a robust solution consider using fastify-mongo or another in the Fastify ecosystem)

server.js

  1. const fastify = require('fastify')({
  2. logger: true
  3. })
  4. fastify.register(require('./our-db-connector'), {
  5. url: 'mongodb://localhost:27017/'
  6. })
  7. fastify.register(require('./our-first-route'))
  8. fastify.listen(3000, function (err, address) {
  9. if (err) {
  10. fastify.log.error(err)
  11. process.exit(1)
  12. }
  13. fastify.log.info(`server listening on ${address}`)
  14. })

our-db-connector.js

  1. const fastifyPlugin = require('fastify-plugin')
  2. const MongoClient = require('mongodb').MongoClient
  3. async function dbConnector (fastify, options) {
  4. const url = options.url
  5. delete options.url
  6. const db = await MongoClient.connect(url, options)
  7. fastify.decorate('mongo', db)
  8. }
  9. // Wrapping a plugin function with fastify-plugin exposes the decorators,
  10. // hooks, and middlewares declared inside the plugin to the parent scope.
  11. module.exports = fastifyPlugin(dbConnector)

our-first-route.js

  1. async function routes (fastify, options) {
  2. const database = fastify.mongo.db('db')
  3. const collection = database.collection('test')
  4. fastify.get('/', async (request, reply) => {
  5. return { hello: 'world' }
  6. })
  7. fastify.get('/search/:id', async (request, reply) => {
  8. const result = await collection.findOne({ id: request.params.id })
  9. if (result.value === null) {
  10. throw new Error('Invalid value')
  11. }
  12. return result.value
  13. })
  14. }
  15. module.exports = routes

Wow, that was fast!Let's recap what we have done here since we've introduced some new concepts.As you can see, we used register both for the database connector and the routes registration. This is one of the best features of Fastify, it will load your plugins in the same order you declare them, and it will load the next plugin only once the current one has been loaded. In this way we can register the database connector in the first plugin and use it in the second (read here to understand how to handle the scope of a plugin). Plugin loading starts when you call fastify.listen(), fastify.inject() or fastify.ready()

We have used the decorate API. Let's take a moment to understand what it is and how it works. A scenario is to use the same code/library in different parts of an application. A solution is to require the code/library that it is needed. This works, but is annoying because of duplicated code repeated and, if needed, long refactors.To solve this Fastify offers the decorate API, which adds custom objects to the Fastify namespace, so that they can be used everywhere.

To dig deeper into how Fastify plugins work, how to develop new plugins, and for details on how to use the whole Fastify API to deal with the complexity of asynchronously bootstrapping an application, read the hitchhiker's guide to plugins.

Loading order of your plugins

To guarantee a consistent and predictable behavior of your application, we highly recommend to always load your code as shown below:

  1. └── plugins (from the Fastify ecosystem)
  2. └── your plugins (your custom plugins)
  3. └── decorators
  4. └── hooks and middlewares
  5. └── your services

In this way you will always have access to all of the properties declared in the current scope.As discussed previously, Fastify offers a solid encapsulation model, to help you build your application as single and independent services. If you want to register a plugin only for a subset of routes, you have just to replicate the above structure.

  1. └── plugins (from the Fastify ecosystem)
  2. └── your plugins (your custom plugins)
  3. └── decorators
  4. └── hooks and middlewares
  5. └── your services
  6. └── service A
  7. └── plugins (from the Fastify ecosystem)
  8. └── your plugins (your custom plugins)
  9. └── decorators
  10. └── hooks and middlewares
  11. └── your services
  12. └── service B
  13. └── plugins (from the Fastify ecosystem)
  14. └── your plugins (your custom plugins)
  15. └── decorators
  16. └── hooks and middlewares
  17. └── your services

Validate your data

Data validation is extremely important and is a core concept of the framework.To validate incoming requests, Fastify uses JSON Schema. Let's look at an example demonstrating validation for routes:

  1. const opts = {
  2. schema: {
  3. body: {
  4. type: 'object',
  5. properties: {
  6. someKey: { type: 'string' },
  7. someOtherKey: { type: 'number' }
  8. }
  9. }
  10. }
  11. }
  12. fastify.post('/', opts, async (request, reply) => {
  13. return { hello: 'world' }
  14. })

This example shows how to pass an options object to the route, which accepts a schema key, that contains all of the schemas for route, body, querystring, params and headers.Read Validation and Serialization to learn more.

Serialize your data

Fastify has first class support for JSON. It is extremely optimized to parse a JSON body and to serialize JSON output.To speed up JSON serialization (yes, it is slow!) use the response key of the schema option like so:

  1. const opts = {
  2. schema: {
  3. response: {
  4. 200: {
  5. type: 'object',
  6. properties: {
  7. hello: { type: 'string' }
  8. }
  9. }
  10. }
  11. }
  12. }
  13. fastify.get('/', opts, async (request, reply) => {
  14. return { hello: 'world' }
  15. })

Simply by specifying a schema as shown, a speed up your of serialization by 2x or even 3x can be achieved. This also helps protect against leaking of sensitive data, since Fastify will serialize only the data present in the response schema. Read Validation and Serialization to learn more.

Extend your server

Fastify is built to be extremely extensible and very minimal, We believe that a bare minimum framework is all that is necessary to make great applications possible.In other words, Fastify is not a "batteries included" framework, and relies on an amazing ecosystem!

Test your server

Fastify does not offer a testing framework, but we do recommend a way to write your tests that uses the features and the architecture of Fastify.Read the testing documentation to learn more!

Run your server from CLI

Fastify also has CLI integration thanks to fastify-cli.

First, install fastify-cli:

  1. npm i fastify-cli

You can also install it globally with -g.

Then, add the following lines to package.json:

  1. {
  2. "scripts": {
  3. "start": "fastify start server.js"
  4. }
  5. }

And create your server file(s):

  1. // server.js
  2. 'use strict'
  3. module.exports = async function (fastify, opts) {
  4. fastify.get('/', async (request, reply) => {
  5. return { hello: 'world' }
  6. })
  7. }

Then run your server with:

  1. npm start

Slides and Videos