Getting started

Introduction

Fastify is a Node.js web framework with a fast router, JSON-schema validation, and a pino logger. This reference targets Fastify v5.

Hello world

import Fastify from 'fastify'

const app = Fastify({ logger: true })

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

await app.listen({ port: 3000 })

listen takes an object. It binds 127.0.0.1 by default; pass host: '0.0.0.0' inside a container.

See: Getting started

Project layout

app.js

import Fastify from 'fastify'

export function build (opts = {}) {
  const app = Fastify(opts)
  app.get('/', async () => ({ hello: 'world' }))
  return app
}

server.js

import { build } from './app.js'

const app = build({ logger: true })
await app.listen({ port: 3000, host: '0.0.0.0' })

Keeping the app separate from listen lets tests call app.inject() without a port.

See: Testing

Graceful shutdown

process.on('SIGTERM', async () => {
  await app.close()
  process.exit(0)
})

close() waits for in-flight requests and runs onClose hooks, so pools and queues close with the server.

See: close

Routing

Shorthand

app.get('/users/:id', async (request) => {
  return { id: request.params.id }
})

app.post('/users', async (request) => {
  return request.body
})

get, post, put, patch, delete, head, options, and trace all take the same arguments.

See: Routes

Full declaration

app.route({
  method: 'GET',
  url: '/users/:id',
  schema: {
    params: {
      type: 'object',
      properties: { id: { type: 'string' } }
    }
  },
  handler: async (request) => ({ id: request.params.id })
})

method also takes an array, and url has an alias path. The full form accepts every hook as an option.

See: Full declaration

Route options

app.get('/admin', {
  logLevel: 'warn',
  bodyLimit: 1024,
  config: { role: 'admin' },
  handler: async () => ({ ok: true })
})

config is arbitrary data, read back as request.routeOptions.config. exposeHeadRoute adds a HEAD sibling for GET.

See: Routes options

Error handling

app.setErrorHandler((error, request, reply) => {
  request.log.error(error)
  reply.code(error.statusCode ?? 500)
    .send({ error: error.message })
})

Throw from a handler and Fastify lands here; the default handler returns { statusCode, error, message }.

See: setErrorHandler

Plugins

Writing a plugin

async function routes (app, opts) {
  app.get('/', async () => ({ hello: opts.name }))
}

export default routes
await app.register(routes, { name: 'world' })

Everything in Fastify is a plugin: routes, decorators, hooks, and third-party packages.

See: Plugins

Encapsulation

app.register(async (scope) => {
  scope.decorate('db', { users: [] })
  scope.get('/internal', async () => scope.db.users)
})

Decorators and hooks stay inside the plugin that added them. Sibling plugins cannot see db, and routes added outside the plugin cannot either.

See: Encapsulation

fastify-plugin

import fp from 'fastify-plugin'

export default fp(async (app) => {
  app.decorate('db', await connect())
}, { name: 'db', fastify: '5.x' })

Wrapping a plugin skips encapsulation, so its decorators land on the parent instance. The metadata names the plugin and pins compatible versions.

See: fastify-plugin

Official plugins

PackageAdds
@fastify/corsCORS headers
@fastify/helmetSecurity headers
@fastify/cookieCookie parsing and signing
@fastify/jwtJWT authentication
@fastify/staticStatic file serving
@fastify/autoloadLoad a folder as plugins
@fastify/swaggerOpenAPI from route schemas

Every fastify-* package moved to the @fastify scope in v4, and the old names are unmaintained.

See: Ecosystem

Hooks

Lifecycle

HookRuns
onRequestFirst; request.body is still undefined
preParsingBefore the payload is parsed
preValidationAfter parsing, before validation
preHandlerBefore the route handler
preSerializationBefore the reply is serialized
onErrorWhen the handler or a hook throws
onSendBefore the reply is flushed
onResponseAfter the reply is sent
onTimeoutWhen handlerTimeout expires
onRequestAbortWhen the client disconnects

Application hooks (onReady, onListen, onClose, onRoute) cover the server, not a request.

See: Lifecycle

Adding hooks

app.addHook('onRequest', async (request) => {
  request.start = Date.now()
})

app.addHook('onResponse', async (request) => {
  request.log.info({ ms: Date.now() - request.start })
})

Never pass a done callback to an async hook; return or throw instead.

See: Hooks

Route hooks

app.get('/private', {
  onRequest: [authenticate],
  preHandler: [loadUser],
  handler: async (request) => ({ user: request.user })
})

Route hooks run after the ones registered on the instance, and each option takes an array.

See: Route-level hooks

Schemas

Validation

const schema = {
  body: {
    type: 'object',
    required: ['name'],
    properties: {
      name: { type: 'string' },
      age: { type: 'integer', minimum: 0 }
    }
  }
}

app.post('/users', { schema }, async (request) => {
  return request.body
})

v5 removed schema shorthand, so every schema needs type. An invalid request gets a 400 before the handler runs.

See: Validation

Response serialization

const schema = {
  response: {
    200: {
      type: 'object',
      properties: {
        id: { type: 'string' },
        name: { type: 'string' }
      }
    }
  }
}

fast-json-stringify compiles the schema and drops properties it does not list, which is both faster and safer than JSON.stringify.

See: Serialization

Shared schemas

app.addSchema({
  $id: 'user',
  type: 'object',
  properties: { id: { type: 'string' } }
})

app.get('/me', {
  schema: { response: { 200: { $ref: 'user#' } } }
}, handler)

addSchema is encapsulated, so a schema added in a plugin stays in that plugin's scope.

See: Adding a shared schema

Request and reply

Request

PropertyHolds
request.bodyParsed payload
request.queryParsed query string
request.paramsRoute parameters
request.headersRequest headers
request.idRequest ID, also in every log line
request.ipClient IP; request.ips when behind a proxy
request.hostHost and port from the Host header
request.protocolhttp or https
request.logRequest-scoped pino logger
request.rawNode.js IncomingMessage

request.signal aborts when the handler times out or the client disconnects.

See: Request

Reply

reply.code(201)
reply.header('X-Request-Id', request.id)
reply.type('text/html')
reply.redirect('/login')        // 302
reply.redirect('/login', 301)
reply.send({ ok: true })
reply.callNotFound()

Returning a value from an async handler is the same as calling reply.send(). reply.sent tells you whether a response has gone out.

See: Reply

Decorators

app.decorate('db', connect())
app.decorateRequest('user', null)
app.decorateReply('cache', null)
app.addHook('preHandler', async (request) => {
  request.user = await request.server.db.findUser(request)
})

Declare request decorators with a scalar such as null or ''. Assigning a reference type at startup throws.

See: Decorators

Logging

Setup

const app = Fastify({
  logger: {
    level: 'info',
    transport: { target: 'pino-pretty' }
  }
})

A custom instance goes in loggerInstance; v5 stopped accepting one in logger.

import pino from 'pino'

const app = Fastify({ loggerInstance: pino({ level: 'warn' }) })

pino-pretty is a dev dependency, not bundled.

See: Logging

Request logs

app.get('/', async (request) => {
  request.log.info({ user: request.user }, 'loading dashboard')
  return { ok: true }
})

Fastify logs one line per request by default. Set disableRequestLogging: true to silence it and log from hooks yourself.

See: Request logging

Redaction

const app = Fastify({
  logger: {
    redact: {
      paths: ['req.headers.authorization', 'req.body.password'],
      censor: '[redacted]'
    }
  }
})

Redaction is a pino feature, so it applies to child loggers such as request.log too.

See: pino redaction

Testing

inject

const response = await app.inject({
  method: 'POST',
  url: '/users',
  payload: { name: 'Ada' }
})

response.statusCode   // 201
response.json()       // { id: '1', name: 'Ada' }

inject() boots every plugin and sends a fake request through the real lifecycle; no port is bound.

See: Testing with HTTP injection

node:test

import test from 'node:test'
import assert from 'node:assert/strict'
import { build } from './app.js'

test('GET /', async (t) => {
  const app = build()
  t.after(() => app.close())

  const res = await app.inject({ method: 'GET', url: '/' })
  assert.equal(res.statusCode, 200)
  assert.deepEqual(res.json(), { hello: 'world' })
})

Call the same build() helper the server calls, so tests exercise the real plugin tree.

See: Testing

0 Comments for this cheatsheet. Write yours!