0
0
NestJSframework~3 mins

Why middleware processes requests before handlers in NestJS - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if you could secure your entire app with just one simple step before any page loads?

The Scenario

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.

The Problem

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.

The Solution

Middleware runs before handlers automatically, so you write the check once and it applies to all requests. This keeps your code clean and secure.

Before vs After
Before
function pageHandler(req, res) {
  if (!req.token) {
    res.send('Please login');
    return;
  }
  // handle page
}
After
app.use(authMiddleware);
function authMiddleware(req, res, next) {
  if (!req.token) {
    res.send('Please login');
  } else {
    next();
  }
}
function pageHandler(req, res) {
  // handle page
}
What It Enables

This lets you add common checks or setup steps once, making your app safer and easier to maintain.

Real Life Example

Think of airport security: everyone passes through a checkpoint before reaching the gates. Middleware is like that checkpoint for your app requests.

Key Takeaways

Middleware runs before handlers to prepare or check requests.

It avoids repeating code in every handler.

This improves security, organization, and code clarity.