How to create and use Middleware for Fastify
overview
Fastify allows you to use middleware to perform processing between requests and responses. Middleware provides access to request objects, response objects, and the following middleware functions: Middleware is used within Fastify’s route handlers.
Here, I will show you how to create middleware with Fastify using the following versions:
Fastify v4.0.0
nodejs v19.7.0
Also, all the code I’ve created so far is listed below. https://github.com/wiblok/Fastify
How to define middleware
There are three ways to use middleware:
- Using middleware functions directly
- How to create a plugin that encapsulates middleware
- How to create middleware as separate files
How to use middleware functions directly
direct.js
const fastify = require('fastify')();
function myMiddleware(request, reply, next) {
// middleware processing
console.log('run middleware');
next();
}
fastify.addHook('preHandler', myMiddleware);
fastify.get('/', (request, reply) => {
reply.send({ message: 'Hello, World!' });
});
fastify.listen({ port: 3000 }, (err) => {
if (err) {
console. error(err);
process.exit(1);
}
console.log('Server is running on port 3000');
});
Commentary
- Create a Fastify instance
const fastify = require("fastify")();
Import the Fastify module and create an instance of it.
- Middleware definition
function myMiddleware(request, reply, next) {
// middleware processing
console.log('run middleware');
next();
}
Define a middleware function myMiddleware
. This function is called before the route handler is executed and prints a message to the console.
- register middleware
fastify.addHook('preHandler', myMiddleware);
Register the middleware on your Fastify instance. It is added as a preHandler
hook, so the myMiddleware
function will be called before the route handler is run.
- Defining route handlers
fastify.get('/', (request, reply) => {
reply.send({ message: 'Hello, World!' });
});
Define a route handler to handle GET requests to the path /
. When a request comes in, it returns an object { message: 'Hello, World!' }
as a response.
- Start server
fastify.listen({ port: 3000 }, (err) => {
if (err) {
console. error(err);
process.exit(1);
}
console.log('Server is running on port 3000');
});
Start the server with an instance of Fastify listening on port 3000. If any error occurs, print the error message to the console and terminate the process. If there are no errors, print the message “Server is running on port 3000” to the console.
test
curl -X GET http://localhost:3000
How to create a plugin that encapsulates middleware
capsule.js
const fastify = require('fastify')();
const myPlugin = (fastify, options, done) => {
function myMiddleware(request, reply, next) {
// middleware processing
console.log('run middleware');
next();
}
fastify.addHook('preHandler', myMiddleware);
done();
};
fastify.register(myPlugin);
fastify.get('/', (request, reply) => {
reply.send({ message: 'Hello, World!' });
});
fastify.listen({ port: 3000 }, (err) => {
if (err) {
console. error(err);
process.exit(1);
}
console.log('Server is running on port 3000');
});
Commentary
- Create a Fastify instance
const fastify = require("fastify")();
Import the Fastify module and create an instance of it.
- plugin definition
const myPlugin = (fastify, options, done) => {
function myMiddleware(request, reply, next) {
// middleware processing
console.log('run middleware');
next();
}
fastify.addHook('preHandler', myMiddleware);
done();
};
Define the plugin myPlugin
. This plugin defines a middleware function myMiddleware
and adds it as a preHandler
hook to the Fastify instance. The myMiddleware
function will be called before the route handler is executed and will print a message to the console.
- Plugin registration
fastify.register(myPlugin);
Register the plugin on your Fastify instance.
- Defining route handlers
fastify.get('/', (request, reply) => {
reply.send({ message: 'Hello, World!' });
});
Define a route handler to handle GET requests to the path /
. When a request comes in, it returns an object { message: 'Hello, World!' }
as a response.
- Start server
fastify.listen({ port: 3000 }, (err) => {
if (err) {
console. error(err);
process.exit(1);
}
console.log('Server is running on port 3000');
});
Start the server with an instance of Fastify listening on port 3000. If any error occurs, print the error message to the console and terminate the process. If there are no errors, print the message “Server is running on port 3000” to the console.
test
curl -X GET http://localhost:3000
This code uses Fastify to define a plugin and register middleware within that plugin. Middleware is executed before the request reaches the handler. The handler sends the message “Hello, World!” in response.
How to create middleware as a separate file
middlewares.js
function myMiddleware(request, reply, next) {
// middleware processing
console.log('run middleware');
next();
}
module. exports = {
myMiddleware
};
middleware-main.js
const fastify = require('fastify')();
const middlewares = require('./middlewares');
fastify.addHook('preHandler', middlewares.myMiddleware);
fastify.get('/', (request, reply) => {
reply.send({ message: 'Hello, World!' });
});
fastify.listen({ port: 3000 }, (err) => {
if (err) {
console. error(err);
process.exit(1);
}
console.log('Server is running on port 3000');
});
Commentary
- Create a Fastify instance
const fastify = require("fastify")();
Import the Fastify module and create an instance of it.
- import middleware
const middlewares = require('./middlewares');
Import the middlewares
module. This module is supposed to export a middleware function named myMiddleware
.
- Add middleware
fastify.addHook('preHandler', middlewares.myMiddleware);
Add the middleware as a preHandler
hook to your Fastify instance. The myMiddleware
function will be called before any route handlers are executed.
- Defining route handlers
fastify.get('/', (request, reply) => {
reply.send({ message: 'Hello, World!' });
});
Define a route handler to handle GET requests to the path /
. When a request comes in, it returns an object { message: 'Hello, World!' }
as a response.
- Start server
fastify.listen({ port: 3000 }, (err) => {
if (err) {
console. error(err);
process.exit(1);
}
console.log('Server is running on port 3000');
});
Start the server with an instance of Fastify listening on port 3000. If any error occurs, print the error message to the console and terminate the process. If there are no errors, print the message “Server is running on port 3000” to the console.
test
curl -X GET http://localhost:3000
This code uses Fastify to create the server and a preHandler hook to define the middleware. Middleware is executed before the request reaches the handler, indicating that the middleware’s work is done. The handler will be executed when a request is sent to the specified path and the appropriate response will be returned.
summary
In this article, we’ve covered how to use middleware with Fastify. Middleware are functions that run before and after a request and are used to customize the handling of requests. Fastify allows you to add middleware using the addHook
method. You can also separate the middleware as a separate file.