## What is Middleware?
Middleware is code that runs between receiving a request and sending a response. It processes requests before they reach your route handlers, and responses before they reach the client.
Think of middleware like airport security checkpoints. Every passenger (request) goes through security (middleware) before boarding (reaching your route).
## How Middleware Works
In Express.js, middleware functions receive request, response, and next function. They can modify the request or response, then call next to pass control to the next middleware.
The middleware runs first, logs the request, then calls next to continue. Without next, the request hangs.
## Common Middleware Use Cases
**Authentication**: Check if user is logged in before allowing access
**Logging**: Record every request for debugging and analytics
**Parsing**: Convert request body from JSON to JavaScript objects
**CORS**: Add headers allowing cross-origin requests
**Compression**: Compress responses to reduce bandwidth
**Rate Limiting**: Prevent abuse by limiting requests per user
**Error Handling**: Catch errors and return proper error responses
## Middleware Chain
Middleware executes in order. Each middleware can modify request or response, call next to continue, send a response and stop the chain, or throw an error.
## Authentication Middleware Example
Create a function that checks for authentication token in headers. If token is missing or invalid, return 401 error. If valid, add user to request object and call next to continue.
## Built-in Middleware
Most frameworks include common middleware:
**Express.js**:
- express.json - Parse JSON bodies
- express.static - Serve static files
- express.urlencoded - Parse form data
**Django**:
- Authentication middleware
- CSRF protection
- Session middleware
**ASP.NET**:
- Authentication
- Routing
- Static files
## Third-Party Middleware
Popular middleware packages handle common tasks like HTTP request logging (morgan), security headers (helmet), CORS handling, gzip compression, cookie parsing, file uploads, and rate limiting.
## Route-Specific Middleware
Apply middleware to specific routes only instead of all routes. Only admin routes require admin check, while public routes have no middleware.
## Error-Handling Middleware
Special middleware for catching errors must have four parameters. Put error middleware last to catch errors from all previous middleware and routes.
## Middleware in Other Frameworks
**Next.js**: Middleware runs at the edge before page renders
**Laravel**: Middleware for routes and route groups
**Django**: Middleware processes every request and response
**Spring Boot**: Filters and interceptors act as middleware
Every web framework has middleware concepts, though names and implementations vary.
## Writing Good Middleware
**Keep it Focused**: Each middleware does one thing well
**Call next**: Always call next unless sending a response
**Handle Errors**: Catch errors and pass to error handler
**Document**: Explain what the middleware does and why
**Order Matters**: Place middleware in logical order (logging first, auth second, etc.)
## Async Middleware
Handle asynchronous operations properly with try-catch blocks and error passing.
## The Bottom Line
Middleware is the backbone of web applications. It keeps your route handlers clean by extracting common logic into reusable pieces.
Authentication, logging, validation, error handling - middleware handles it all. Learn to write and use middleware effectively, and your code becomes cleaner, more maintainable, and more secure.