Middleware — Complete Guide
Middleware — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of MEAN Stack Tutorial on Toolliyo Academy.
On this page
MEAN Stack Tutorial · Lesson 35 of 100
Middleware
Stack → Projects
Stack · 1 — Pieces · ~6 min · MEAN — Node.js & Express
What is this?
Middleware functions run between request and response — logging, auth, parsing — in Express order for MeanVerse APIs.
Why should you care?
Cross-cutting concerns belong in middleware, not duplicated in every route handler.
See it live — copy this example
Paste into your MeanVerse project (Angular + Express + MongoDB), then run with ng serve / node / mongosh as noted.
export function requestLogger(req: Request, _res: Response, next: NextFunction) {
const start = Date.now();
_res.on('finish', () => {
console.error(`${req.method} ${req.path} ${_res.statusCode} ${Date.now() - start}ms`);
});
next();
}
export function requireRole(role: string) {
return (req: Request, res: Response, next: NextFunction) => {
if (!req.user?.roles.includes(role)) return res.status(403).json({ message: 'Forbidden' });
next();
};
}
What happened?
- next() passes control downstream.
- requireRole returns middleware closure checking JWT roles.
- Logger attaches on finish event for timing.
Practice next
- Add requestLogger globally with app.use.
- Create auth middleware verifying JWT on req.headers.authorization.
- Apply requireRole('admin') only on admin routes.
- Add correlation-id middleware from x-request-id header.
- Skip logging for /health in conditional middleware.
Remember
Middleware order matters. Reuse auth and logging globally. Factory pattern for parameterized middleware.
Audit trail
Banking regulator requires who accessed which account API.
Outcome: Logger middleware records user id and route on every call.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!