How to Add Middleware in Express: A Complete Guide
Middleware functions are essential in Express.js — a popular Node.js web framework — for handling requests and responses systematically. This tutorial walks you through the concept of Express middleware, its types, and practical steps to add middleware to your Express applications to improve functionality, modularity, and efficiency.
What is Middleware in Express?
Middleware in Express are functions executed sequentially during the request-response cycle. They can execute code, modify request and response objects, end the request-response cycle, or call the next middleware function. This design makes middleware powerful for logging, authentication, data parsing, error handling, and more.
Types of Middleware
- Application-level Middleware: Bound to an Express app instance, effective globally or on specific routes.
- Router-level Middleware: Attached to an Express
Routerinstance for modular route handling. - Built-in Middleware: Provided by Express, such as
express.staticto serve static files. - Error-handling Middleware: Special middleware with four parameters to catch and handle errors.
- Third-party Middleware: Utilities like body-parser (Official site) for parsing request bodies.
Prerequisites
- Node.js installed on your system.
- Basic knowledge of JavaScript and Node.js.
- Express.js installed or a starter Express project created.
Step-by-Step Instructions to Add Middleware in Express
Step 1: Create an Express Application
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Step 2: Using Application-level Middleware
Define middleware globally for all routes using app.use(). For example, logging each request:
app.use((req, res, next) => {
console.log(`${req.method} request for '${req.url}'`);
next(); // Pass control to the next middleware or route handler
});
Step 3: Adding Built-in Middleware
Express includes useful built-in middleware. For instance, serving static files from a directory called “public”:
app.use(express.static('public'));
Step 4: Using Third-party Middleware
Install body parser to parse JSON request bodies (note: in Express 4.16+, body parsing is built-in):
npm install body-parser
Then use it:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
Step 5: Creating Router-level Middleware
Use Express Router to modularize your app and apply middleware only on specific routes:
const router = express.Router();
// Middleware only for this router
router.use((req, res, next) => {
console.log('Router-level middleware');
next();
});
router.get('/items', (req, res) => {
res.send('Item list');
});
app.use('/api', router);
Step 6: Adding Error-handling Middleware
This middleware catches errors and sends custom responses:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
Troubleshooting Tips
- Always call
next()in your middleware unless ending the response. Omittingnext()causes requests to hang. - Be careful about the order of middleware registration. Express executes middleware in the order added.
- Use error-handling middleware at the end of the middleware stack for effective error capturing.
- When using third-party middleware, ensure correct installation and importing.
Summary Checklist
- Understand middleware types: application-level, router-level, built-in, third-party, error-handling.
- Use
app.use()to add middleware globally or by route path. - Leverage Express built-in middleware for static assets and JSON parsing.
- Install and incorporate third-party middleware when needed.
- Modularize with router-level middleware for cleaner code.
- Implement error-handling middleware for graceful failure responses.
- Maintain correct middleware order and always call
next()when necessary.
Middleware unlocks the full power of Express and provides a structured approach to handle your Node.js app’s requests and responses effectively. For more on Express in general, check out our post on How to Create Routes in Express to complement your learning.
