Express.js Middleware Explained
Imagine you're at an airport. Before boarding your flight, you go through multiple checkpoints: security check, passport verification, baggage screening. Each checkpoint examines something and either lets you proceed or stops you. In Express.js, **middleware** works exactly like these checkpoints!
What is Middleware?
Middleware functions are functions that have access to the request object (`req`), the response object (`res`), and the `next` function in the application's request-response cycle. They can:
- Execute any code.
- Make changes to the request and response objects.
- End the request-response cycle.
- Call the next middleware in the stack.
Think of middleware as a pipeline. The request flows through each middleware function, and each one can process it, modify it, or stop it from going further.
Middleware Structure
function middlewareFunction(req, res, next) { <!-- Do something --> console.log('Middleware executed'); <!-- Either end the response or call next() --> next(); <!-- Pass control to the next middleware -->}
<!-- Using the middleware -->app.use(middlewareFunction);Types of Middleware
| Type | Description |
|---|---|
| Application-level | Bound to the app instance using `app.use()` or `app.METHOD()`. |
| Router-level | Bound to a router instance using `router.use()`. |
| Error-handling | Takes four parameters `(err, req, res, next)`. |
| Built-in | Provided by Express (e.g., `express.json()`). |
| Third-party | Installed via npm (e.g., `cors`, `morgan`). |
Simple Middleware Example
const express = require('express');const app = express();
<!-- Logger middleware -->app.use((req, res, next) => { console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`); next(); <!-- Pass to next middleware/route -->});
<!-- Route -->app.get('/', (req, res) => { res.send('Hello World');});
app.listen(3000);The `next()` Function
The `next()` function is crucial – it passes control to the next middleware. If you don't call `next()` or end the response (with `res.send()`), the request will hang forever.
app.use((req, res, next) => { console.log('Middleware 1'); next(); <!-- Goes to next middleware -->});
app.use((req, res, next) => { console.log('Middleware 2'); res.send('Response from middleware 2'); <!-- Ends the cycle -->});
app.use((req, res, next) => { <!-- This will NEVER run because response already sent --> console.log('Middleware 3');});Two Minute Drill
- Middleware functions process requests before they reach route handlers.
- They have access to `req`, `res`, and `next`.
- Call `next()` to pass control to the next middleware, or send a response to end the cycle.
- Middleware can be application-level, router-level, error-handling, built-in, or third-party.
- Order of middleware matters – they execute in the order they're defined.
Need more clarification?
Drop us an email at career@quipoinfotech.com
