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 .
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.
1 Request ---> [ Middleware 1 (Logger) ] ---> [ Middleware 2 (Auth) ] ---> [ Route Handler ] ---> Response
A middleware function must either:
1 End the request-response cycle by sending a response (res.send(), res.json()), OR
2 Call next() to pass control to the subsequent middleware function in the stack.
1 // A simple custom logger middleware
2 const requestLogger = ( req , res , next ) => {
3 const start = Date . now ( ) ;
4 res . on ( 'finish' , ( ) => {
5 const duration = Date . now ( ) - start ;
6 console . log ( ` [ ${ req . method } ] ${ req . originalUrl } - ${ res . statusCode } ( ${ duration } ms) ` ) ;
7 } ) ;
8 next ( ) ; // MUST call next() to prevent the request from hanging!
9 } ;
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:
1 app . use ( express . json ( ) ) ;
2 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):
1 const adminRouter = express . Router ( ) ;
2
3 adminRouter . use ( ( req , res , next ) => {
4 if ( ! req . user || req . user . role !== 'admin' ) {
5 return res . status ( 403 ) . json ( { error : 'Forbidden: Admin access required' } ) ;
6 }
7 next ( ) ;
8 } ) ;
9
10 adminRouter . get ( '/dashboard' , ( req , res ) => res . json ( { stats : 'admin data' } ) ) ;
11 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 • Knowledge Check
Multiple Choice Questions What happens if a middleware function fails to send a response and also forgets to call next()?
A Express throws an immediate syntax error.
B The client request hangs indefinitely until the browser or client socket times out.
C The request automatically redirects to /home.
D The server process restarts.
How does Express distinguish an Error-Handling middleware from regular application middleware?
A Error middleware must be defined inside an error.js file.
B Error-handling middleware accepts exactly 4 parameters: (err, req, res, next).
C Error middleware uses app.catch() instead of app.use().
D Error middleware requires a TypeScript decorator.
Which built-in middleware serves static assets like images, CSS, and client-side JavaScript bundles directly from a directory?
A express.files()
B express.static()
C express.serve()
D express.assets()
What is the execution order of middleware in an Express application?
A In reverse alphabetical order of function names.
B In the exact top-to-bottom order in which they are declared using app.use().
C Simultaneously on parallel worker threads.
D Randomly based on CPU load.
Why should global middleware like express.json() and logging be registered near the very top of app.js?
A Because Node.js cannot read bottom lines of code.
B To ensure they process incoming requests before the requests reach specific route handlers.
C To prevent CSS from overriding JavaScript.
D Express will not start otherwise.