Integrating Middleware and Hooks in Fastify for Server-Side Development
Written on
Chapter 1: Introduction to Fastify
Fastify is a lightweight framework built on Node.js, designed for creating backend web applications. This article delves into the process of developing backend applications using Fastify.
Section 1.1: Middleware Integration
Middleware functionality is not included by default in Fastify version 3 and later. To incorporate Express-like middleware, you must install the fastify-express or middie plugin. Here is how you can set it up:
const fastify = require('fastify')();
const start = async () => {
try {
await fastify.register(require('fastify-express'));
fastify.use(require('cors')());
fastify.get('/', function (request, reply) {
reply.send({ hello: 'world' });});
await fastify.listen(3000, '0.0.0.0');
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
In the code above, we add await fastify.register(require('fastify-express')) and fastify.use(require('cors')()) to enable the fastify-express plugin along with CORS middleware.
Subsection 1.1.1: Restricting Middleware to Specific Paths
To limit middleware execution to specific routes, you can specify paths as shown below:
const fastify = require('fastify')({});
const path = require('path');
const start = async () => {
try {
await fastify.register(require('fastify-express'));
const serveStatic = require('serve-static');
fastify.use('/css', serveStatic(path.join(__dirname, '/assets')));
fastify.use('/css/(.*)', serveStatic(path.join(__dirname, '/assets')));
fastify.use(['/css', '/js'], serveStatic(path.join(__dirname, '/assets')));
fastify.get('/', function (request, reply) {
reply.send({ hello: 'world' });});
await fastify.listen(3000, '0.0.0.0');
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
In this example, fastify.use is called with the middleware's designated path as the first argument, and the middleware function as the second. Note that this approach does not work with routes containing parameters. Fastify provides alternatives for commonly used middleware, such as fastify-helmet for security headers, fastify-cors for CORS support, and fastify-static for serving static files.
Section 1.2: Utilizing Hooks
Hooks can be registered in Fastify using the fastify.addHook method. For instance:
const fastify = require('fastify')({});
const asyncMethod = () => Promise.resolve('foo');
const start = async () => {
try {
fastify.addHook('onRequest', async (request, reply) => {
await asyncMethod();
return;
});
fastify.get('/', function (request, reply) {
reply.send({ hello: 'world' });});
await fastify.listen(3000, '0.0.0.0');
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
Here, addHook is used for the onRequest event. Alternatively, you can implement it as follows:
const fastify = require('fastify')({});
fastify.addHook('onRequest', (request, reply, done) => {
done();
});
const start = async () => {
try {
fastify.get('/', function (request, reply) {
reply.send({ hello: 'world' });});
await fastify.listen(3000, '0.0.0.0');
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
In this case, the done function is called to indicate that the hook has completed its execution.
Chapter 2: Practical Examples
The first video, "Fastify and React CRUD with Context API, Hooks and Tailwind JIT Part II - YouTube," provides a practical demonstration of implementing CRUD operations using Fastify and React.
The second video, "Custom Cache plugin in Fastify using hooks and node-cache - YouTube," showcases how to create a custom caching solution in Fastify using hooks.
Conclusion
In conclusion, Fastify allows for the integration of Express middleware and hooks, enhancing the development capabilities for server-side applications.