Starting with Fastify v3.0.0, middleware is not supported out of the box and requires an external plugin such as fastify-express
or middie
.
An example of registering the fastify-express
plugin to then use
Express middleware:
await fastify.register(require('fastify-express'))
fastify.use(require('cors')())
fastify.use(require('dns-prefetch-control')())
fastify.use(require('frameguard')())
fastify.use(require('hsts')())
fastify.use(require('ienoopen')())
fastify.use(require('x-xss-protection')())
You can also use middie
, which provides support for simple Express-style middleware but with improved performance:
await fastify.register(require('middie'))
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.
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.
const path = require('path')
const serveStatic = require('serve-static')
// Single path
fastify.use('/css', serveStatic(path.join(__dirname, '/assets')))
// Wildcard path
fastify.use('/css/(.*)', serveStatic(path.join(__dirname, '/assets')))
// Multiple paths
fastify.use(['/css', '/js'], serveStatic(path.join(__dirname, '/assets')))
Fastify offers some alternatives to the most commonly used middleware, such as fastify-helmet
in case of helmet
, fastify-cors
for cors
and fastify-static
for serve-static
.