Getting-Started | Fastify (2024)

Getting Started

Hello! Thank you for checking out Fastify!

This document aims to be a gentle introduction to the framework and itsfeatures. It is an elementary preface with examples and links to other parts ofthe documentation.

Let's start!

Install

Install with npm:

npm i fastify

Install with yarn:

yarn add fastify

Your first server

Let's write our first server:

// Require the framework and instantiate it

// ESM
import Fastify from 'fastify'

const fastify = Fastify({
logger: true
})
// CommonJs
const fastify = require('fastify')({
logger: true
})

// Declare a route
fastify.get('/', function (request, reply) {
reply.send({ hello: 'world' })
})

// Run the server!
fastify.listen({ port: 3000 }, function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
// Server is now listening on ${address}
})

If you are using ECMAScript Modules (ESM) in your project, be sure toinclude "type": "module" in your package.json.

{
"type": "module"
}

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

// ESM
import Fastify from 'fastify'

const fastify = Fastify({
logger: true
})
// CommonJs
const fastify = require('fastify')({
logger: true
})

fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})

/**
* Run the server!
*/
const start = async () => {
try {
await fastify.listen({ port: 3000 })
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()

Awesome, that was easy.

Unfortunately, writing a complex application requires significantly more codethan this example. A classic problem when you are building a new application ishow to handle multiple files, asynchronous bootstrapping, and the architectureof your code.

Fastify offers an easy platform that helps to solve all of the problems outlinedabove, and more!

Note

The above examples, and subsequent examples in this document, default tolistening only on the localhost 127.0.0.1 interface. To listen on allavailable IPv4 interfaces the example should be modified to listen on0.0.0.0 like so:

fastify.listen({ port: 3000, host: '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 systemsupports 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 aplugin.

Before digging into it, let's see how it works!

Let's declare our basic server, but instead of declaring the route inside theentry point, we'll declare it in an external file (check out the routedeclaration docs).

// ESM
import Fastify from 'fastify'
import firstRoute from './our-first-route'
/**
* @type {import('fastify').FastifyInstance} Instance of Fastify
*/
const fastify = Fastify({
logger: true
})

fastify.register(firstRoute)

fastify.listen({ port: 3000 }, function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
// Server is now listening on ${address}
})
// CommonJs
/**
* @type {import('fastify').FastifyInstance} Instance of Fastify
*/
const fastify = require('fastify')({
logger: true
})

fastify.register(require('./our-first-route'))

fastify.listen({ port: 3000 }, function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
// Server is now listening on ${address}
})
// our-first-route.js

/**
* Encapsulates the routes
* @param {FastifyInstance} fastify Encapsulated Fastify Instance
* @param {Object} options plugin options, refer to https://fastify.dev/docs/latest/Reference/Plugins/#plugin-options
*/
async function routes (fastify, options) {
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})
}

//ESM
export default routes;

// CommonJs
module.exports = routes

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

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

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

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

npm i fastify-plugin @fastify/mongodb

server.js

// ESM
import Fastify from 'fastify'
import dbConnector from './our-db-connector'
import firstRoute from './our-first-route'

/**
* @type {import('fastify').FastifyInstance} Instance of Fastify
*/
const fastify = Fastify({
logger: true
})
fastify.register(dbConnector)
fastify.register(firstRoute)

fastify.listen({ port: 3000 }, function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
// Server is now listening on ${address}
})
// CommonJs
/**
* @type {import('fastify').FastifyInstance} Instance of Fastify
*/
const fastify = require('fastify')({
logger: true
})

fastify.register(require('./our-db-connector'))
fastify.register(require('./our-first-route'))

fastify.listen({ port: 3000 }, function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
// Server is now listening on ${address}
})

our-db-connector.js

// ESM
import fastifyPlugin from 'fastify-plugin'
import fastifyMongo from '@fastify/mongodb'

/**
* @param {FastifyInstance} fastify
* @param {Object} options
*/
async function dbConnector (fastify, options) {
fastify.register(fastifyMongo, {
url: 'mongodb://localhost:27017/test_database'
})
}

// Wrapping a plugin function with fastify-plugin exposes the decorators
// and hooks, declared inside the plugin to the parent scope.
export default fastifyPlugin(dbConnector)

// CommonJs
/**
* @type {import('fastify-plugin').FastifyPlugin}
*/
const fastifyPlugin = require('fastify-plugin')


/**
* Connects to a MongoDB database
* @param {FastifyInstance} fastify Encapsulated Fastify Instance
* @param {Object} options plugin options, refer to https://fastify.dev/docs/latest/Reference/Plugins/#plugin-options
*/
async function dbConnector (fastify, options) {
fastify.register(require('@fastify/mongodb'), {
url: 'mongodb://localhost:27017/test_database'
})
}

// Wrapping a plugin function with fastify-plugin exposes the decorators
// and hooks, declared inside the plugin to the parent scope.
module.exports = fastifyPlugin(dbConnector)

our-first-route.js

/**
* A plugin that provide encapsulated routes
* @param {FastifyInstance} fastify encapsulated fastify instance
* @param {Object} options plugin options, refer to https://fastify.dev/docs/latest/Reference/Plugins/#plugin-options
*/
async function routes (fastify, options) {
const collection = fastify.mongo.db.collection('test_collection')

fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})

fastify.get('/animals', async (request, reply) => {
const result = await collection.find().toArray()
if (result.length === 0) {
throw new Error('No documents found')
}
return result
})

fastify.get('/animals/:animal', async (request, reply) => {
const result = await collection.findOne({ animal: request.params.animal })
if (!result) {
throw new Error('Invalid value')
}
return result
})

const animalBodyJsonSchema = {
type: 'object',
required: ['animal'],
properties: {
animal: { type: 'string' },
},
}

const schema = {
body: animalBodyJsonSchema,
}

fastify.post('/animals', { schema }, async (request, reply) => {
// we can use the `request.body` object to get the data sent by the client
const result = await collection.insertOne({ animal: request.body.animal })
return result
})
}

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 theregistration of the routes.

This is one of the best features of Fastify, it will load your plugins in thesame order you declare them, and it will load the next plugin only once thecurrent one has been loaded. In this way, we can register the database connectorin the first plugin and use it in the second (readhere to understand how to handle thescope of a plugin).

Plugin loading starts when you call fastify.listen(), fastify.inject() orfastify.ready()

The MongoDB plugin uses the decorate API to add custom objects to the Fastifyinstance, making them available for use everywhere. Use of this API isencouraged to facilitate easy code reuse and to decrease code or logicduplication.

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

Loading order of your plugins

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

└── plugins (from the Fastify ecosystem)
└── your plugins (your custom plugins)
└── decorators
└── hooks
└── your services

In this way, you will always have access to all of the properties declared inthe current scope.

As discussed previously, Fastify offers a solid encapsulation model, to help youbuild your application as single and independent services. If you want toregister a plugin only for a subset of routes, you just have to replicate theabove structure.

└── plugins (from the Fastify ecosystem)
└── your plugins (your custom plugins)
└── decorators
└── hooks
└── your services

└── service A
│ └── plugins (from the Fastify ecosystem)
│ └── your plugins (your custom plugins)
│ └── decorators
│ └── hooks
│ └── your services

└── service B
└── plugins (from the Fastify ecosystem)
└── your plugins (your custom plugins)
└── decorators
└── hooks
└── your services

Validate your data

Data validation is extremely important and a core concept of the framework.

To validate incoming requests, Fastify uses JSONSchema.

(JTD schemas are loosely supported, but jsonShorthand must be disabled first)

Let's look at an example demonstrating validation for routes:

/**
* @type {import('fastify').RouteShorthandOptions}
* @const
*/
const opts = {
schema: {
body: {
type: 'object',
properties: {
someKey: { type: 'string' },
someOtherKey: { type: 'number' }
}
}
}
}

fastify.post('/', opts, async (request, reply) => {
return { hello: 'world' }
})

This example shows how to pass an options object to the route, which accepts aschema key that contains all of the schemas for route, body, querystring,params, and headers.

Read Validation andSerialization to learn more.

Serialize your data

Fastify has first-class support for JSON. It is extremely optimized to parseJSON bodies and serialize JSON output.

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

/**
* @type {import('fastify').RouteShorthandOptions}
* @const
*/
const opts = {
schema: {
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
}
}

fastify.get('/', opts, async (request, reply) => {
return { hello: 'world' }
})

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

Parsing request payloads

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

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

/**
* @type {import('fastify').RouteShorthandOptions}
*/
const opts = {}
fastify.post('/', opts, async (request, reply) => {
return request.body
})

Read Content-Type Parser to learn moreabout Fastify's default parsing functionality and how to support other contenttypes.

Extend your server

Fastify is built to be extremely extensible and minimal, we believe that abare-bones framework is all that is necessary to make great applicationspossible.

In other words, Fastify is not a "batteries included" framework, and relies onan amazing ecosystem!

Test your server

Fastify does not offer a testing framework, but we do recommend a way to writeyour 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 tofastify-cli.

First, install fastify-cli:

npm i fastify-cli

You can also install it globally with -g.

Then, add the following lines to package.json:

{
"scripts": {
"start": "fastify start server.js"
}
}

And create your server file(s):

// server.js
'use strict'

module.exports = async function (fastify, opts) {
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})
}

Then run your server with:

npm start

Slides and Videos

Getting-Started | Fastify (2024)

FAQs

What is Fastify CLI? ›

Command line tools for Fastify. Generate, write, and run an application with one single command!

What companies are using fastify? ›

List of companies using Fastify in India
CompanyCountryTechnologies
IO DataLabsIndiaFastify
ComUnus Technologies Pvt LtdIndiaFastify
Hupp TechnologiesIndiaFastify
Eminence InnovationIndiaFastify
6 more rows

Why is Fastify so fast? ›

Fastify provides full encapsulation for plug-ins, automatically parses JSON with relatively faster rendering, and provides quick routing. Among other benefits, Fastify also has a cleaner syntax for writing async code in controllers. Fastify is consistently faster than Express by 2–3 seconds.

What is fastify? ›

Fastify is a web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture. It is inspired by Hapi and Express and as far as we know, it is one of the fastest web frameworks in town.

Is Fastify free? ›

Fastify is a web framework, for Node. js, available free and open source under an MIT license.

Is Fastify better than Express? ›

If you prioritize performance and scalability, Fastify is the clear winner. However, if ease of use and a mature ecosystem are more important, Express might be the better choice. Consider your project's specific needs to make the best decision.

Is fastify worth learning? ›

Fastify offers a compelling alternative to Express and other Node. js frameworks by focusing on performance, modern JavaScript features, and a robust plugin system. Its advantages make it particularly suitable for high-performance applications where efficiency and scalability are paramount.

Should I use NestJS or fastify? ›

Performance Overhead: Due to its extensive feature set and abstractions, NestJS may not match the performance of more lightweight frameworks like Fastify. Complexity: The extensive feature set and opinionated structure can lead to a steeper learning curve for beginners or those coming from other frameworks.

What does fastify register do? ›

register creates a new Fastify context, which means that if you perform any changes on the Fastify instance, those changes will not be reflected in the context's ancestors. In other words, encapsulation!

What are the disadvantages of fastify? ›

Disadvantages of Fastify

Being a relatively newer web framework, Fastify may have a smaller community compared to more established frameworks. This can result in limited availability of community-developed plugins, extensions, and community-driven support resources.

What is the difference between fastify and Hapi? ›

Fastify uses a schema-based routing system, where routes are defined using JSON schemas. This allows for easy validation and serialization of request and response payloads. On the other hand, hapi uses a more traditional callback-based routing system, where routes are defined using JavaScript code.

Who created Fastify? ›

This is a tremendous accolade for everyone who has contributed to the project that started 3 years ago. Fastify is fully made in Italy, between Udine and Forlì, where co-creator Tomas Della Vedova and I live respectively.

Who uses Fastify? ›

Some of the companies that use Fastify include BrainFinance, AmeriSave, Hedra Consulting, Reydix GmbH, BizAway, Attestis, Peter Park System GmbH, LRQA - sustainability, Pipedrive, Grupo Boticário and many more. You can find a complete list of 761 companies that use Fastify on TheirStack.com.

What is the philosophy of fastify? ›

Fastify believes in the power of community. In their philosophy, the community is considered a first-class citizen. Now, more than ever, Fastify needs the community's support to continue evolving and surpass the reputation of other stagnating frameworks.

How popular is fastify? ›

Is fastify popular? The npm package fastify receives a total of 333,156 weekly downloads. As such, fastify popularity was classified as an influential project. Visit the popularity section on Snyk Advisor to see the full health analysis.

What is the use of CLI tool? ›

What are the use cases of a CLI?
  • System administration. System administrators use CLIs to fix system-related issues, check the operating system configurations, and change or update configurations on remote machines. ...
  • Software development. ...
  • Cloud computing. ...
  • Network management.

What is a CLI scanner? ›

A command-line scanner is a software tool used to analyze, detect, and remove malicious files from a computer system. It operates through text-based commands in a command-line interface (CLI), allowing users to perform tasks without the need for a graphical user interface (GUI).

What is the CLI tool in Windows? ›

The Azure Command-Line Interface (CLI) is a cross-platform command-line tool that can be installed locally on Windows computers. You can use the Azure CLI for Windows to connect to Azure and execute administrative commands on Azure resources.

Top Articles
Minecraft Guide to Pillagers: Raids, outposts, defenses and more
Download EventLog Analyzer | Free edition
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
Things To Do In Atlanta Tomorrow Night
Non Sequitur
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Otter Bustr
Selly Medaline
Latest Posts
Article information

Author: Pres. Lawanda Wiegand

Last Updated:

Views: 5420

Rating: 4 / 5 (71 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Pres. Lawanda Wiegand

Birthday: 1993-01-10

Address: Suite 391 6963 Ullrich Shore, Bellefort, WI 01350-7893

Phone: +6806610432415

Job: Dynamic Manufacturing Assistant

Hobby: amateur radio, Taekwondo, Wood carving, Parkour, Skateboarding, Running, Rafting

Introduction: My name is Pres. Lawanda Wiegand, I am a inquisitive, helpful, glamorous, cheerful, open, clever, innocent person who loves writing and wants to share my knowledge and understanding with you.