This was answered when Fastify 2 was the main version. This answer may not be correct for Fastify 3
While Fastify is compatible with Express/Restify method signature, it isn't exactly the same values being passed in. The method signature is:
/**
* Generic middleware method
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} res
*/
const middleware = (req, res) => {
}
fastify.use(middleware)
When using .use
, Fastify only deals with the Node.js HTTP classes
which do not provide the .params
or .query
fields.
Express adds these fields as a nicety to developers. If the middleware you use
relies on those features, unfortunately, it will not be a direct drop in.
All is not lost
If you choose to migrate your middleware to Fastify, the .params
and .query
fields are available on the Request
object.
Using the middleware in your question, this is what the Fastify version would
look like.
fastify.addHook('onRequest', function(request, reply, done) {
console.log('query', request.query);
console.log('params', request.params);
done();
})
Fastify is asking developers to think more in terms of Hooks and less in terms of Middleware. This provides more flexibility and greater speed but can be a little more complicated to write at times.
Additional reading
The Lifecycle and
Hooks documentation on the Fastify
site give more detail on how these pieces work together.
The Middleware documentation
provides more detail on what features are supported.
Somewhat related, using Plugins
you are able to scope to a particular path.
References
Express middleware support
From the Middleware documentation:
Furthermore, methods added by Express and Restify to the enhanced versions of
req and res are not supported in Fastify middlewares.
and
Express modifies the prototype of the node core Request and Response objects
heavily so Fastify cannot guarantee full middleware compatibility.
Express adding .params
and .query
Express adding .query
to request
and where Express runs the query middleware
Express adding parameters to route.