If you need a visual feedback to understand when the middlewares are executed take a look to the lifecycle page.
Fastify middlewares 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
res are not supported in Fastify middlewares.
Also, if you are using a middleware that bundles different, smaller middlewares, such as helmet, we recommend to use the single modules to get better performances.
const fastify = require('fastify')()
const helmet = require('fastify-helmet')
Remember that middlewares can be encapsulated, this means that you can decide where your middlewares should run by using
register as explained in the plugins guide.
Fastify middlewares also do not expose the
send method or other methods specific to the Fastify Reply instance. This is because Fastify wraps the incoming
res Node instances using the Request and Reply objects internally, but this is done after the middlewares phase. If you need to create a middleware you have to use the Node
res instances. Otherwise, you can use the
preHandler hook that 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 wildcard is 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')))