Middleware Pipeline: Application-Level, Router-Level & Third-Party0%

Middleware Pipeline: Application-Level, Router-Level & Third-Party

Beginner12 min read•Updated: Jul 11, 2026
Study MaterialsCheatsheet

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.

Output
Request ---> [ Middleware 1 (Logger) ] ---> [ Middleware 2 (Auth) ] ---> [ Route Handler ] ---> Response

A middleware function must either:

  1. 1
    End the request-response cycle by sending a response (res.send(), res.json()), OR
  2. 2
    Call next() to pass control to the subsequent middleware function in the stack.
JavaScript
// A simple custom logger middleware
const requestLogger = (req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
console.log(`[${req.method}] ${req.originalUrl} - ${res.statusCode} (${duration}ms)`);
});
next(); // MUST call next() to prevent the request from hanging!
};

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:

JavaScript
app.use(express.json());
app.use(requestLogger);

2. Router-Level Middleware

Bound to an instance of express.Router(). Perfect for modular route scoping (e.g. protecting all admin routes):

JavaScript
const adminRouter = express.Router();
 
adminRouter.use((req, res, next) => {
if (!req.user || req.user.role !== 'admin') {
return res.status(403).json({ error: 'Forbidden: Admin access required' });
}
next();
});
 
adminRouter.get('/dashboard', (req, res) => res.json({ stats: 'admin data' }));
app.use('/admin', adminRouter);

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).


Interactive Quiz

Multiple Choice Questions

Question 1
What happens if a middleware function fails to send a response and also forgets to call next()?
Question 2
How does Express distinguish an Error-Handling middleware from regular application middleware?
Question 3
Which built-in middleware serves static assets like images, CSS, and client-side JavaScript bundles directly from a directory?
Question 4
What is the execution order of middleware in an Express application?
Question 5
Why should global middleware like express.json() and logging be registered near the very top of app.js?

Next Lesson

RESTful API Design Standards: HTTP Verbs, Status Codes & Idempotency

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext