Express Middleware & Request Pipeline
Middleware functions have access to request, response objects and the next middleware function. They execute in order and can modify req/res or end the request.
Basic Middleware
const express = require('express');
const app = express();
// Application-level middleware
app.use((req, res, next) => {
console.log('Time:', Date.now());
next(); // Pass to next middleware
});
// Logging middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.path}`);
next();
});
// Parse JSON body
app.use(express.json());
// Parse URL-encoded body
app.use(express.urlencoded({ extended: true }));
// Static files
app.use(express.static('public'));
// Route-specific middleware
app.get('/api/users', authMiddleware, (req, res) => {
res.json(users);
});
// Error-handling middleware (4 parameters)
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Internal Server Error' });
});Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free