What if you could secure your entire app with just one simple step before any page loads?
Why middleware processes requests before handlers in NestJS - The Real Reasons
Imagine building a web app where every request needs to be checked for a login token before showing the page. You try to add this check inside each page handler manually.
Manually adding checks in every handler is slow, repetitive, and easy to forget. It leads to bugs where some pages skip the check, causing security holes.
Middleware runs before handlers automatically, so you write the check once and it applies to all requests. This keeps your code clean and secure.
function pageHandler(req, res) {
if (!req.token) {
res.send('Please login');
return;
}
// handle page
}app.use(authMiddleware);
function authMiddleware(req, res, next) {
if (!req.token) {
res.send('Please login');
} else {
next();
}
}
function pageHandler(req, res) {
// handle page
}This lets you add common checks or setup steps once, making your app safer and easier to maintain.
Think of airport security: everyone passes through a checkpoint before reaching the gates. Middleware is like that checkpoint for your app requests.
Middleware runs before handlers to prepare or check requests.
It avoids repeating code in every handler.
This improves security, organization, and code clarity.