How to Create Middleware in Express: Simple Guide
In Express, create middleware by defining a function with
req, res, and next parameters. Use app.use() or route methods to apply it, and call next() to pass control to the next middleware or route handler.Syntax
A middleware function in Express has three parameters: req (request), res (response), and next (a function to pass control). You define it as a function and then use app.use() or attach it to specific routes.
- req: Holds request data like headers and body.
- res: Used to send a response back to the client.
- next: Call this to move to the next middleware or route handler.
javascript
function myMiddleware(req, res, next) { // Your code here next(); } app.use(myMiddleware);
Example
This example shows a middleware that logs the request method and URL, then passes control to the next handler. It demonstrates how middleware can be used to add functionality before routes respond.
javascript
import express from 'express'; const app = express(); // Middleware to log request info function logger(req, res, next) { console.log(`${req.method} ${req.url}`); next(); } app.use(logger); app.get('/', (req, res) => { res.send('Hello from Express!'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
GET /
Common Pitfalls
Common mistakes include forgetting to call next(), which causes the request to hang, or sending multiple responses. Also, placing middleware in the wrong order can prevent it from running as expected.
Always call next() unless you end the response with res.send() or similar.
javascript
/* Wrong: missing next() causes hang */ function badMiddleware(req, res, next) { console.log('This will hang the request'); // next() is missing here } /* Right: calls next() to continue */ function goodMiddleware(req, res, next) { console.log('This passes control'); next(); }
Quick Reference
- Middleware signature:
(req, res, next) => {} - Use
app.use()for global middleware. - Call
next()to continue to next middleware or route. - Order matters: middleware runs in the order added.
- Middleware can modify
reqandresobjects.
Key Takeaways
Middleware functions have three parameters: req, res, and next.
Always call next() unless sending a response to avoid hanging requests.
Use app.use() to apply middleware globally or attach to specific routes.
Middleware runs in the order it is added to the app.
Middleware can modify request and response objects before reaching routes.