Middleware in Express.js is a function that executes during the request-response cycle. It can modify the request or response objects, end the request-response cycle, or call the next middleware in the stack.
Think of middleware as layers through which a request passes before reaching the final route handler.
Application-Level Middleware
Bound to an instance of express() using app.use() or app.METHOD().
Example: Logging, authentication, request parsing.
Router-Level Middleware
Bound to an instance of express.Router().
Helps organize routes and middleware for specific route groups.
Built-in Middleware
Express provides some built-in middleware, e.g.:
express.json() – Parses JSON request bodies.
express.urlencoded() – Parses URL-encoded request bodies.
Third-Party Middleware
Middleware provided by npm packages, e.g.:
cors – Enable Cross-Origin Resource Sharing.
morgan – HTTP request logging.
body-parser – Parsing request bodies (now mostly replaced by express.json()).
Error-Handling Middleware
Middleware that catches errors and sends responses.
Signature: (err, req, res, next).
req – Request object
res – Response object
next – Function to pass control to the next middleware
Example 1: Application-Level Middleware
Example 2: Using Built-in Middleware
Example 3: Error-Handling Middleware
Incoming request hits first middleware in the stack.
Middleware modifies req/res or performs actions.
Calls next() → passes control to next middleware or route handler.
If next() is not called → request stops here.
Errors can be passed using next(err) → goes to error-handling middleware.
Middleware can be global (app.use) or route-specific.
Order of middleware matters.
Middleware is essential for tasks like:
Logging requests
Parsing request bodies
Authentication & authorization
Error handling
Middleware is one of the core concepts in Express.js, making it flexible and modular.
Take quizzes related to this topic and see where you stand!
Start Quiz Now