Node.js – Middleware
Subject: nodejs
Node.js – Middleware
In Node.js web application development, particularly when using Express.js, middleware functions act as intermediary handlers in the request-response cycle. Middleware has access to req, res, and a next() function that passes control.
Why Use Middleware?
- Request Pre-processing: Handle headers, body parsing, or modify the request.
 - Response Modification: Edit or enhance outgoing responses.
 - Cross-Cutting Concerns: Centralize logic like logging, authentication.
 - Flow Control: Middleware can halt or forward requests.
 - Reusability: Use middleware in multiple routes or apps.
 
How Middleware Works (Pipeline Analogy)
- Request enters the server.
 - Passes through a stack of middleware functions.
 - Each middleware can:
- Run logic or modify 
req/res. - Call 
next()to pass control. - End the cycle by sending a response.
 
 - Run logic or modify 
 - If 
next()is called, final route handler executes. 
Middleware Setup Example (Express.js)
Installation:
File: app.js
Test the Server
- GET 
http://localhost:3000 - POST 
http://localhost:3000/submit-data 
Expected JSON Response:
Types of Middleware in Express
- Application-level: 
app.use()– global middleware. - Router-level: middleware tied to 
express.Router(). - Error-handling: 4 arguments 
(err, req, res, next). - Built-in: 
express.json(),express.static(), etc. - Third-party: 
morgan,helmet,cookie-parser. 
Key Takeaways
- Middleware intercepts and processes requests.
 - Essential for modular code and cross-cutting logic.
 - Always call 
next()to proceed. - Runs sequentially in the order defined.
 - Types include application, router, error-handling, and third-party.
 - Results in cleaner, scalable applications.