This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Fastify Cheatsheet

A quick reference guide for Fastify: routing, JSON schema validation, reply helpers, plugin architecture, hooks, and template rendering.

· Published

Fastify is an efficient and low-overhead web framework highly focused on providing the best developer experience and blazing-fast throughput.

Getting Started

Introduction

Fastify delivers outstanding throughput and performance, featuring schema-based compilation, validation, and a powerful plugin architecture.

Hello World

const fastify = require('fastify')()

fastify.get('/', (req, reply) => {
  reply.send({ hello: 'world' })
})

fastify.listen(3000, err => {
  if (err) throw err
  const port = fastify.server.address().port
  console.log(`server listening on ${port}`)
})

Routing

Route Declaration

fastify.route({
  method: 'GET',
  url: '/',
  schema: { ··· },
  handler: (req, reply) => { ··· },
  beforeHandler: (req, reply, done) => { ··· }
})

Shorthand Methods

fastify.get(path, [options], handler)
fastify.head(path, [options], handler)
fastify.post(path, [options], handler)
fastify.put(path, [options], handler)
fastify.delete(path, [options], handler)
fastify.options(path, [options], handler)
fastify.patch(path, [options], handler)

Async / Await Handlers

fastify.get('/', options, async (req, reply) => {
  return data
  // or
  reply.send(data)
})

With async handlers, you can simply return the payload or invoke reply.send(data).

Request & Reply

Request Object

request.query
request.body
request.params
request.headers
request.req  // Node.js core incoming request
request.log.info('hello')

See: Request.

Reply Object

Response Headers

reply.code(404)
reply.header('Content-Type', 'text/html')
reply.type('text/html')

Redirects

reply.redirect('/foo')
reply.redirect(302, '/foo')

Sending Data

reply.send(payload)
reply.sent // → true|false

See: Reply.

JSON Schema Validation

Defining a Schema

const schema = {
  querystring: {
    name: { type: 'string' },
    excitement: { type: 'integer' }
  },
  response: {
    200: {
      type: 'object',
      properties: {
        hello: { type: 'string' }
      }
    }
  }
}

Passing Schema to Route

fastify.get('/', { schema }, (req, reply) => {
  ···
})

Route Options Object

fastify.route({
  method: 'GET',
  url: '/',
  schema,
  handler: (req, reply) => { ··· }
})

Defining a JSON schema enables high-speed validation and automatic serialization speedups.

See: Validation and Serialization.

Plugins

Registering a Function

fastify.register(
  require('./route'),
  err => { if (err) throw err }
)

route.js

module.exports = (fastify, options, next) => {
  fastify.get('/', (req, reply) => { ··· })
  next()
}

See: Plugins.

Registering Multiple Plugins

fastify.register([
  require('./another-route'),
  require('./yet-another-route')
], opts, (err) => {
  if (err) throw err
})

Route Prefixes

fastify.register(
  require('./route'),
  { prefix: '/v1' }
)

Prefixes will be automatically prepended to all routes defined in that plugin context.

fastify-plugin

const fp = require('fastify-plugin')

module.exports = fp((fastify, opts, next) => {
  fastify.decorate('utility', () => {})
  next()
}, '0.x')

Allows plugins to skip scope encapsulation and share decorators across parent scopes.

Middleware & Templates

Middleware Integration

fastify.use(require('cors')())
fastify.use(require('dns-prefetch-control')())
fastify.use(require('frameguard')())
fastify.use(require('hide-powered-by')())
fastify.use(require('hsts')())
fastify.use(require('ienoopen')())
fastify.use(require('x-xss-protection')())

See: Middleware.

Template Rendering with point-of-view

const fastify = require('fastify')()

fastify.register(require('point-of-view'), {
  engine: {
    ejs: require('ejs')
  },
  templates: '/templates',
  options: {}
})

fastify.get('/', (req, reply) => {
  reply.view('/templates/index.ejs', { text: 'text' })
})

Supports template engines like ejs, pug, handlebars, and marko.

Related topics