Middleware Pipeline: Application-Level, Router-Level & Third-Party
Middleware Pipeline: Application-Level, Router-Level & Third-Party
Middleware functions are the fundamental building blocks of an Express.js backend. In Express, everything from parsing request bodies and authenticating sessions to logging traffic and handling CORS is executed through a pipeline of middleware functions.
1. What is Middleware?
A middleware function has access to the Request object (req), the Response object (res), and the next function in the application’s request-response cycle.
A middleware function must either:
- 1End the request-response cycle by sending a response (
res.send(),res.json()), OR - 2Call
next()to pass control to the subsequent middleware function in the stack.
2. The 5 Types of Middleware in Express
1. Application-Level Middleware
Bound directly to the app instance using app.use() or app.METHOD(). Runs on every matching path across the entire application:
2. Router-Level Middleware
Bound to an instance of express.Router(). Perfect for modular route scoping (e.g. protecting all admin routes):
3. Built-In Middleware
Included natively in Express (express.json(), express.urlencoded(), express.static('public')).
4. Third-Party Middleware
Installed from NPM (cors, helmet, morgan, cookie-parser).
5. Error-Handling Middleware
Special middleware defined with 4 arguments: (err, req, res, next).
Multiple Choice Questions
next()?express.json() and logging be registered near the very top of app.js?RESTful API Design Standards: HTTP Verbs, Status Codes & Idempotency
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.