
Now that we are familiar with the concept of middleware let’s try to deep dive into different kinds of middleware and their use cases.
Let me give you an instance of the libraries that i had back in my college.
Each library was special and had a unique
Imagine visiting three different libraries, each with a unique purpose and functionality.
These libraries represent middleware, where each performs a specific task or handles a unique scenario, depending on its use case.
Library 1: Small Library: Basic Access
- This library is in a quiet neighborhood with a small collection of books.
- The librarian at the entrance checks your membership card. If it’s valid, you’re allowed to borrow any book directly.
Use case:
This library is like a basic authentication middleware, ensuring only valid members can access the system without adding unnecessary steps. It’s simple and efficient.
Library 2: Big Library: Comprehensive Services
- This library is large and serves many users.
- Your membership is verified at the entrance, and overdue books are checked.
- Inside, a digital system offers personalized book recommendations based on your past borrowing history.
- For special collections, you must request additional access through a separate process.
- Finally, you can borrow books at the checkout desk.
Use case:
This library works like a middleware chain, where each step does something useful or checks a specific rule. It’s designed for bigger systems that need more features and processes.
Research Library: Specialized Access
- This library is for researchers and professionals.
- To enter, you must show proof of your profession, like a university ID or research credentials.
- Inside, the library provides access to specialized resources, such as rare books, journals, or databases, tailored for academic or professional use.
- There’s also a team to help you retrieve hard-to-find resources or sign up for workshops.
Use case:
This library acts like custom middleware, focusing on specialized users with specific needs, ensuring they get the right tools and data for their tasks.
In this analogy, each library showcases how middleware can serve different purposes based on the requirements:
- The Small Library demonstrates basic middleware, performing essential tasks like authentication to ensure quick and simple access.
- The Big Library highlights a chain of middleware, where multiple layers work together to provide personalized services, additional checks, and enhanced user experiences.
- The Research Library represents custom middleware, designed for specific, advanced use cases to cater to unique audiences with tailored features.
If you’re visiting both the Main Library and the Research Wing in your college library system, you experience the benefits of both sections seamlessly.
Combining Access and Privileges
- Main Library Visit:
- As you enter the Main Library, the system identifies you and checks your borrowing history.
- You are then provided with a list of personalized book recommendations tailored to your previous activity.
- Transition to the Research Wing:
- When you proceed to the Research Wing, you show your research credentials.
- Along with access to the exclusive resources, such as rare books and journals, you also receive guidance from specialized staff to make the most of your visit.
In this case, you benefit from all functionalities: personalized book recommendations from the Main Library and advanced privileges from the Research Wing.
So in this case if let’s say you are visiting the big and specilised library you will get an access to some recommnedatainos as well as some speciliassed privileges for being a part of research library so in the same way if the request passes through multiple middlewares it also get’s some added functionalities.
Coding Example:
We want to add specific functionalities to our req (request) object, such as book recommendations and access permissions. To achieve this, we’ll use middleware to modify the req object before it reaches the routes.
const express = require(‘express’);
const app = express();
// Middleware for Big Library
app.use(‘/big-library’, (req, res, next) => {
req.recommendations = [‘The Hobbit’, ‘Harry Potter’]; // Adding recommendations
next();
});
// Middleware for Research Library
app.use(‘/research-library’, (req, res, next) => {
req.access = ‘granted’; // Granting access
next();
});
// Route for Big Library
app.get(‘/big-library’, (req, res) => {
res.send(`Big Library Recommendations: ${req.recommendations.join(‘, ‘)}`);
});
// Route for Research Library
app.get(‘/research-library’, (req, res) => {
res.send(`Research Library Access: ${req.access}`);
});
// Start the server
app.listen(3000, () => console.log(‘Server running on http://localhost:3000’));
Key Features:
- Big Library Middleware: Adds a list of book recommendations.
- Research Library Middleware: Grants access to special resources.
How It Works:
- We use middleware to modify the req object by adding properties (req.recommendations and req.access) as the request travels through.
- Middleware: Each middleware function runs before the final route handler, so by the time the request reaches the route, it has the necessary information attached to it.
Why Middleware Is Useful Here:
- Since the request passes through the middleware, the necessary data (like book recommendations or access flags) gets added to it before the final route handler processes the request.
This makes it easy to manage and organize logic, especially when there are multiple steps or checks before a final action (like fetching a list of books or granting access).
—————————————————–
Middleware Analogy
Similarly, when a request in a web application passes through multiple middlewares, each one adds specific functionalities or checks before the request reaches its final destination.
For example:
- Initial Middleware:
- A middleware for the Main Library enriches the request with data such as req.recommendations—a list of book recommendations based on the user’s preferences.
- Next Middleware:
- A middleware for the Research Wing further adds req.access—specialized privileges or access flags for advanced resources.
When the request reaches the final route handler, it has accumulated all the necessary enhancements. The route can now use these properties to provide a more tailored response to the user.