Middleware
Middleware
Starting with Fastify v3.0.0, middleware is not supported out of the box and
requires an external plugin such as
@fastify/express or
@fastify/middie.
An example of registering the
@fastify/express plugin to 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')())
@fastify/middie can also be used,
which provides support for simple Express-style middleware with improved
performance:
await fastify.register(require('@fastify/middie'))
fastify.use(require('cors')())
Middleware can be encapsulated, allowing control over where it runs using
register as explained in the plugins guide.
Fastify middleware does 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. To create middleware,
use the Node req and res instances. Alternatively, use the preHandler hook
that already has the Fastify Request and
Reply instances. For more information, see
Hooks.
Restrict middleware execution to certain paths
To run middleware under certain paths, pass the path as the first parameter to
use.
🛈 Note: This does not support routes with parameters (e.g.
/user/:id/comments) and wildcards are not supported in multiple paths.
const path = require('node: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')))
Alternatives
Fastify offers alternatives to commonly used middleware, such as
@fastify/helmet for
helmet,
@fastify/cors for
cors, and
@fastify/static for
serve-static.