Getting-Started

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 preface with examples and links to other parts of the documentation.

Let’s start!

Install

Install with npm:

  1. npm i fastify

Install with yarn:

  1. yarn add fastify

Your first server

Let’s write our first server:

  1. // Require the framework and instantiate it
  2. // ESM
  3. import Fastify from 'fastify'
  4. const fastify = Fastify({
  5. logger: true
  6. })
  7. // CommonJs
  8. const fastify = require('fastify')({
  9. logger: true
  10. })
  11. // Declare a route
  12. fastify.get('/', function (request, reply) {
  13. reply.send({ hello: 'world' })
  14. })
  15. // Run the server!
  16. fastify.listen({ port: 3000 }, function (err, address) {
  17. if (err) {
  18. fastify.log.error(err)
  19. process.exit(1)
  20. }
  21. // Server is now listening on ${address}
  22. })

If you are using ECMAScript Modules (ESM) in your project, be sure to include “type”: “module” in your package.json.

  1. {
  2. "type": "module"
  3. }

Do you prefer to use async/await? Fastify supports it out-of-the-box.

  1. // ESM
  2. import Fastify from 'fastify'
  3. const fastify = Fastify({
  4. logger: true
  5. })
  6. // CommonJs
  7. const fastify = require('fastify')({
  8. logger: true
  9. })
  10. fastify.get('/', async (request, reply) => {
  11. return { hello: 'world' }
  12. })
  13. /**
  14. * Run the server!
  15. */
  16. const start = async () => {
  17. try {
  18. await fastify.listen({ port: 3000 })
  19. } catch (err) {
  20. fastify.log.error(err)
  21. process.exit(1)
  22. }
  23. }
  24. 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 to handle multiple files, asynchronous bootstrapping, and the architecture of your code.

Fastify offers an easy platform that helps to solve all of the problems outlined above, 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({ port: 3000, host: '0.0.0.0' }, function (err, address) {
  2. if (err) {
  3. fastify.log.error(err)
  4. process.exit(1)
  5. }
  6. fastify.log.info(`server listening on ${address}`)
  7. })

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 another type of) container using 0.0.0.0 or :: would be the easiest method for exposing the application.

Your first plugin

As with JavaScript, where 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 (check out the route declaration docs).

  1. // ESM
  2. import Fastify from 'fastify'
  3. import firstRoute from './our-first-route.js'
  4. /**
  5. * @type {import('fastify').FastifyInstance} Instance of Fastify
  6. */
  7. const fastify = Fastify({
  8. logger: true
  9. })
  10. fastify.register(firstRoute)
  11. fastify.listen({ port: 3000 }, function (err, address) {
  12. if (err) {
  13. fastify.log.error(err)
  14. process.exit(1)
  15. }
  16. // Server is now listening on ${address}
  17. })
  1. // CommonJs
  2. /**
  3. * @type {import('fastify').FastifyInstance} Instance of Fastify
  4. */
  5. const fastify = require('fastify')({
  6. logger: true
  7. })
  8. fastify.register(require('./our-first-route'))
  9. fastify.listen({ port: 3000 }, function (err, address) {
  10. if (err) {
  11. fastify.log.error(err)
  12. process.exit(1)
  13. }
  14. // Server is now listening on ${address}
  15. })
  1. // our-first-route.js
  2. /**
  3. * Encapsulates the routes
  4. * @param {FastifyInstance} fastify Encapsulated Fastify Instance
  5. * @param {Object} options plugin options, refer to https://fastify.dev/docs/latest/Reference/Plugins/#plugin-options
  6. */
  7. async function routes (fastify, options) {
  8. fastify.get('/', async (request, reply) => {
  9. return { hello: 'world' }
  10. })
  11. }
  12. //ESM
  13. export default routes;
  14. // CommonJs
  15. module.exports = routes

In this example, we used the register API, which is the core of the Fastify framework. It is the only way to add routes, plugins, et cetera.

At the beginning of this guide, we noted that Fastify provides a foundation that assists with asynchronous bootstrapping of your application. Why is this important?

Consider the scenario where a database connection is needed to handle data storage. The database connection needs to be available before the server is accepting connections. How do we address this problem?

A typical solution is to use a complex callback, or promises - a 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.

First, install fastify-plugin and @fastify/mongodb:

  1. npm i fastify-plugin @fastify/mongodb

server.js

  1. // ESM
  2. import Fastify from 'fastify'
  3. import dbConnector from './our-db-connector.js'
  4. import firstRoute from './our-first-route.js'
  5. /**
  6. * @type {import('fastify').FastifyInstance} Instance of Fastify
  7. */
  8. const fastify = Fastify({
  9. logger: true
  10. })
  11. fastify.register(dbConnector)
  12. fastify.register(firstRoute)
  13. fastify.listen({ port: 3000 }, function (err, address) {
  14. if (err) {
  15. fastify.log.error(err)
  16. process.exit(1)
  17. }
  18. // Server is now listening on ${address}
  19. })
  1. // CommonJs
  2. /**
  3. * @type {import('fastify').FastifyInstance} Instance of Fastify
  4. */
  5. const fastify = require('fastify')({
  6. logger: true
  7. })
  8. fastify.register(require('./our-db-connector'))
  9. fastify.register(require('./our-first-route'))
  10. fastify.listen({ port: 3000 }, function (err, address) {
  11. if (err) {
  12. fastify.log.error(err)
  13. process.exit(1)
  14. }
  15. // Server is now listening on ${address}
  16. })

our-db-connector.js

  1. // ESM
  2. import fastifyPlugin from 'fastify-plugin'
  3. import fastifyMongo from '@fastify/mongodb'
  4. /**
  5. * @param {FastifyInstance} fastify
  6. * @param {Object} options
  7. */
  8. async function dbConnector (fastify, options) {
  9. fastify.register(fastifyMongo, {
  10. url: 'mongodb://localhost:27017/test_database'
  11. })
  12. }
  13. // Wrapping a plugin function with fastify-plugin exposes the decorators
  14. // and hooks, declared inside the plugin to the parent scope.
  15. export default fastifyPlugin(dbConnector)
  1. // CommonJs
  2. /**
  3. * @type {import('fastify-plugin').FastifyPlugin}
  4. */
  5. const fastifyPlugin = require('fastify-plugin')
  6. /**
  7. * Connects to a MongoDB database
  8. * @param {FastifyInstance} fastify Encapsulated Fastify Instance
  9. * @param {Object} options plugin options, refer to https://fastify.dev/docs/latest/Reference/Plugins/#plugin-options
  10. */
  11. async function dbConnector (fastify, options) {
  12. fastify.register(require('@fastify/mongodb'), {
  13. url: 'mongodb://localhost:27017/test_database'
  14. })
  15. }
  16. // Wrapping a plugin function with fastify-plugin exposes the decorators
  17. // and hooks, declared inside the plugin to the parent scope.
  18. module.exports = fastifyPlugin(dbConnector)

our-first-route.js

  1. /**
  2. * A plugin that provide encapsulated routes
  3. * @param {FastifyInstance} fastify encapsulated fastify instance
  4. * @param {Object} options plugin options, refer to https://fastify.dev/docs/latest/Reference/Plugins/#plugin-options
  5. */
  6. async function routes (fastify, options) {
  7. const collection = fastify.mongo.db.collection('test_collection')
  8. fastify.get('/', async (request, reply) => {
  9. return { hello: 'world' }
  10. })
  11. fastify.get('/animals', async (request, reply) => {
  12. const result = await collection.find().toArray()
  13. if (result.length === 0) {
  14. throw new Error('No documents found')
  15. }
  16. return result
  17. })
  18. fastify.get('/animals/:animal', async (request, reply) => {
  19. const result = await collection.findOne({ animal: request.params.animal })
  20. if (!result) {
  21. throw new Error('Invalid value')
  22. }
  23. return result
  24. })
  25. const animalBodyJsonSchema = {
  26. type: 'object',
  27. required: ['animal'],
  28. properties: {
  29. animal: { type: 'string' },
  30. },
  31. }
  32. const schema = {
  33. body: animalBodyJsonSchema,
  34. }
  35. fastify.post('/animals', { schema }, async (request, reply) => {
  36. // we can use the `request.body` object to get the data sent by the client
  37. const result = await collection.insertOne({ animal: request.body.animal })
  38. return result
  39. })
  40. }
  41. 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 for both the database connector and the registration of the routes.

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()

The MongoDB plugin uses the decorate API to add custom objects to the Fastify instance, making them available for use everywhere. Use of this API is encouraged to facilitate easy code reuse and to decrease code or logic duplication.

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 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
  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 just have to replicate the above structure.

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

Validate your data

Data validation is extremely important and 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. /**
  2. * @type {import('fastify').RouteShorthandOptions}
  3. * @const
  4. */
  5. const opts = {
  6. schema: {
  7. body: {
  8. type: 'object',
  9. properties: {
  10. someKey: { type: 'string' },
  11. someOtherKey: { type: 'number' }
  12. }
  13. }
  14. }
  15. }
  16. fastify.post('/', opts, async (request, reply) => {
  17. return { hello: 'world' }
  18. })

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 JSON bodies and serialize JSON output.

To speed up JSON serialization (yes, it is slow!) use the response key of the schema option as shown in the following example:

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

By specifying a schema as shown, you can speed up serialization by a factor of 2-3. This also helps to protect against leakage of potentially sensitive data, since Fastify will serialize only the data present in the response schema. Read Validation and Serialization to learn more.

Parsing request payloads

Fastify parses 'application/json' and 'text/plain' request payloads natively, with the result accessible from the Fastify request object at request.body.

The following example returns the parsed body of a request back to the client:

  1. /**
  2. * @type {import('fastify').RouteShorthandOptions}
  3. */
  4. const opts = {}
  5. fastify.post('/', opts, async (request, reply) => {
  6. return request.body
  7. })

Read Content-Type Parser to learn more about Fastify’s default parsing functionality and how to support other content types.

Extend your server

Fastify is built to be extremely extensible and minimal, we believe that a bare-bones 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 use the features and 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