Middleware
Understand middleware in Express.js — how it works, how to create custom middleware, and how to use third-party middleware.
Middleware functions are the backbone of Express.js. They run between receiving a request and sending a response — allowing you to add functionality like logging, authentication, parsing, and error handling.
How Middleware Works
Middleware functions have access to the req, res, and next objects:
app.use((req, res, next) => {
console.log('New request:');
console.log('Path:', req.path);
console.log('Method:', req.method);
next(); // Pass control to the next middleware/route
});
Important: Always call next() unless you're ending the request. Without it, the request hangs forever.
Types of Middleware
- Application-level —
app.use()runs on every request - Route-level — Runs only on specific routes
- Built-in — Comes with Express (e.g.,
express.static()) - Third-party — Installed via NPM (e.g.,
morgan,cors)
Static Files Middleware
Serve CSS, images, and JavaScript files from a public/ folder:
app.use(express.static('public'));
Now any file in public/ is accessible. For example, public/styles.css can be loaded as /styles.css in your HTML.
Morgan — Logging Middleware
const morgan = require('morgan');
app.use(morgan('dev'));
Morgan logs details about every request — method, URL, status code, and response time. Essential for debugging.
Custom Middleware Example
// Authentication check middleware
const requireAuth = (req, res, next) => {
if (req.headers.authorization) {
next(); // User is authenticated
} else {
res.status(401).send('Unauthorized');
}
};
// Use on specific routes
app.get('/dashboard', requireAuth, (req, res) => {
res.render('dashboard');
});