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.
Practice
Solution
Step 1: Understand middleware role
Middleware runs before handlers to prepare or validate requests, like checking authentication or adding data.Step 2: Compare with other options
Middleware does not send responses after handlers or replace handlers; it only processes requests early.Final Answer:
To prepare or check the request before the handler uses it -> Option DQuick Check:
Middleware prepares requests = D [OK]
- Thinking middleware runs after handlers
- Believing middleware replaces handlers
- Assuming middleware delays requests
Solution
Step 1: Identify middleware flow control
In NestJS, callingnext()passes control to the next middleware or handler.Step 2: Eliminate incorrect options
Returning response or throwing error stops flow; calling handler manually is not standard.Final Answer:
Callnext()function -> Option BQuick Check:
Use next() to continue middleware chain [OK]
- Forgetting to call next(), causing request hang
- Trying to call handler directly inside middleware
- Returning response without next() when not ending request
export function logger(req, res, next) {
console.log('Middleware start');
next();
console.log('Middleware end');
}Solution
Step 1: Analyze middleware execution order
Console logs before and after next() run synchronously; first logs "Middleware start".Step 2: Understand next() behavior
Calling next() passes control but does not pause middleware; "Middleware end" logs after next() call.Final Answer:
"Middleware start" then "Middleware end" -> Option AQuick Check:
Logs before and after next() run in order [OK]
- Thinking next() pauses middleware execution
- Assuming logs after next() run later
- Believing next() stops middleware code
export function authMiddleware(req, res, next) {
if (!req.headers.authorization) {
res.status(401).send('Unauthorized');
return;
}
next();
}Solution
Step 1: Review middleware flow control
If authorization header is missing, response is sent but next() is still called, causing request to continue incorrectly.Step 2: Fix flow by returning early
To stop processing after sending response, return immediately without calling next().Final Answer:
next() is called even after sending response, causing errors -> Option CQuick Check:
Don't call next() after sending response [OK]
- Calling next() after response ends
- Not returning early to stop middleware
- Misunderstanding middleware flow control
Solution
Step 1: Understand middleware purpose
Middleware runs before handlers, so adding data toreqhere makes it available later.Step 2: Correct order of operations
Assignreq.timestampbefore callingnext()so handlers see the value.Final Answer:
Addreq.timestamp = Date.now()in middleware, then callnext()-> Option AQuick Check:
Add data before next() to share with handlers [OK]
- Adding data after next(), so handlers miss it
- Trying to add data in handlers instead of middleware
- Sending data only in response headers
Ready to prove it?
Pass the test and this pattern moves unknown
