Fastify Cheat Sheet

From WikiOD

Here is the cheatsheat of Fastify and basic guide on how to use Fastify

Getting started[edit | edit source]

Introduction[edit | edit source]

{: .-intro}

Fastify lets you create HTTP servers in Node.js with good performance. This guide targets fastify v0.28.x.

Hello world[edit | edit source]

{: .-prime}

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}`)
})

Plugins[edit | edit source]

app.js[edit | edit source]

fastify.register(require('./route'))

route.js[edit | edit source]

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

  next()
})

Compose your app functionality into plugins. Plugins are simply functions.

See: Plugins

Routes[edit | edit source]

Writing routes[edit | edit source]

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

Shorthand declarations[edit | edit source]

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

Async/await[edit | edit source]

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

When using async functions, you can either return data or use reply.send.

Request/reply[edit | edit source]

Request[edit | edit source]

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

See: Request

Reply[edit | edit source]

Response headers[edit | edit source]

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

Redirects[edit | edit source]

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

Sending[edit | edit source]

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

See: Reply

JSON schema[edit | edit source]

Define a JSON schema[edit | edit source]

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

Pass it to the route[edit | edit source]

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

{: data-line=“1”}

or (same as above)[edit | edit source]

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

{: data-line=“4”}

By defining a JSON schema, you get validation and improved performance.

See: Validation and serialization

Plugins[edit | edit source]

With function[edit | edit source]

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

{: data-line=“3”}

route.js[edit | edit source]

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

See: Register

Multiple[edit | edit source]

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

You can pass arrays to register().

Register with prefix[edit | edit source]

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

This prefixes all routes in that module.

Helmet[edit | edit source]

const helmet = require('fastify-helmet')

fastify.register(helmet)

See: fastify-helmet

fastify-plugin[edit | edit source]

const fp = require('fastify-plugin')

module.exports = fp((fastify, opts, next) => {
  // your plugin code
  fastify.decorate('utility', () => {})

  next()
}, '0.x')

Allows you to limit Fastify versions via semver, and allows you not make a new Fastify scope.

See: fastify-plugin

Decorators[edit | edit source]

Middleware[edit | edit source]

Middleware[edit | edit source]

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

Compatible with Express and Restify middlewares. (Don’t use these middleware, these are covered by fastify-helmet.)

See: Middlewares

Template rendering[edit | edit source]

point-of-view[edit | edit source]

const fastify = require('fastify')()

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

{: data-line=“3”}

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

{: data-line=“2”}

Support ejs, pug, handlebars and marko.

See: point-of-view

Options[edit | edit source]

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

templates lets you update the templates folder. options are options passed onto the template engines.

Credit:rstacruz