Middleware

From Fastify v3, middleware support does not come out of the box with the framework itself, but it’s offered as an external plugin via fastify-express and middie.

If you need to use an express style middleware you can use one of the two plugins above:

  1. await fastify.register(require('fastify-express'))
  2. fastify.use(require('cors')())
  3. fastify.use(require('dns-prefetch-control')())
  4. fastify.use(require('frameguard')())
  5. fastify.use(require('hsts')())
  6. fastify.use(require('ienoopen')())
  7. fastify.use(require('x-xss-protection')())

You can also use middie, which provides support for simple Express-style middlewares but with improved performances:

  1. await fastify.register(require('middie'))
  2. fastify.use(require('cors')())

Remember that middleware can be encapsulated, this means that you can decide where your middleware should run by using register as explained in the plugins guide.

Fastify middleware also do not expose the send method or other methods specific to the Fastify Reply instance. This is because Fastify wraps the incoming req and res Node instances using the Request and Reply objects internally, but this is done after the middleware phase. If you need to create middleware, you have to use the Node req and res instances. Otherwise, you can use the preHandler hook which already has the Request and Reply Fastify instances. For more information, see Hooks.

Restrict middleware execution to a certain path(s)

If you need to run a middleware only under certain path(s), just pass the path as first parameter to use and you are done!

Note that this does not support routes with parameters, (eg: /user/:id/comments) and wildcards are not supported in multiple paths.

  1. const path = require('path')
  2. const serveStatic = require('serve-static')
  3. // Single path
  4. fastify.use('/css', serveStatic(path.join(__dirname, '/assets')))
  5. // Wildcard path
  6. fastify.use('/css/(.*)', serveStatic(path.join(__dirname, '/assets')))
  7. // Multiple paths
  8. fastify.use(['/css', '/js'], serveStatic(path.join(__dirname, '/assets')))

Alternatives

Fastify offers some alternatives to the most commonly used middlewares, such as fastify-helmet in case of helmet, fastify-cors for cors and fastify-static for serve-static.