Middleware

Fastify provides an asynchronous middleware engine out-of-the-box, which is compatible with Express and Restify middleware.

For help with understanding when middleware is executed, take a look at the lifecycle page.

Fastify middleware don't support the full syntax middleware(err, req, res, next), because error handling is done inside Fastify. Furthermore, methods added by Express and Restify to the enhanced versions of req and res are not supported in Fastify middlewares.

Also, if you are using middleware that bundles different, smaller middleware, such as helmet, we recommend using the single modules for better performance.

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

or, in the specific case of helmet, you can use the fastify-helmetplugin, which is an optimized helmet integration for fastify:

  1. const fastify = require('fastify')()
  2. const helmet = require('fastify-helmet')
  3. fastify.register(helmet)

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

Express middleware compatibility

Express modifies the prototype of the node core Request and Response objects heavily so Fastify cannot guarantee full middleware compatibility. Express specific functionality such as res.sendFile(), res.send() or express.Router() instances will not work with Fastify. For example, cors is compatible while passport is not.