Node.js 30 🟢 Middleware Architecture and Custom Middleware Creation in Express
Express is middleware. The application itself is a middleware function, the router is a middleware function, and every route handler is a middleware function. The framework’s entire request-response pipeline is a chain of functions that receive the request, the response, and a next callback. Understanding middleware is understanding Express. The previous chapters used middleware—express.json(), logger, requireAuth—without explaining the architecture underneath. This chapter explains it: what middleware is, how the chain is constructed, how errors propagate, and how to write custom middleware that is correct, composable, and testable.
Key point: A middleware function is a function with the signature (req, res, next). It can read or modify the request and response, end the request-response cycle by sending a response, or call next() to pass control to the next middleware in the chain. An error-handling middleware has four arguments: (err, req, res, next). It is called when next(err) is invoked or when a handler throws. The order in which middleware is registered determines the order in which it runs.
Why middleware architecture matters
The composition problem. A web request needs many things done to it before the handler runs: the body parsed, the session loaded, the user authenticated, the request logged, the headers set. Express does not provide these as features of the framework. It provides them as middleware, and the application composes the chain. The architecture is the composition mechanism.
The order problem. Middleware runs in the order it is registered. A body parser must run before a handler that reads req.body. An authentication middleware must run before a route that requires a user. An error handler must run after every route. The order is the application’s responsibility, and getting it wrong produces bugs that are hard to trace.
The error problem. Express distinguishes between regular middleware and error-handling middleware by the number of arguments. A function with three arguments is a regular middleware. A function with four arguments is an error handler. When next(err) is called, Express skips all regular middleware and jumps to the next error handler. When the error handler calls next(err) again, it passes the error to the next error handler. This is how errors propagate through the chain.
The reusability problem. Middleware is a function. It can be packaged, published, and installed. The Express ecosystem has thousands of middleware modules: body-parser, cors, helmet, morgan, cookie-parser, express-session, passport. Each one is a function with the (req, res, next) signature, and each one can be mounted in the application. Writing custom middleware means joining this ecosystem with functions that are specific to the application.
The async problem. Middleware can be asynchronous. An authentication middleware might query the database. A rate-limiting middleware might increment a counter in Redis. Express 4 does not handle promises returned from middleware; Express 5 does. In Express 4, an async middleware must call next() explicitly and catch its own errors. In Express 5, a rejected promise is passed to next() automatically.
a. The middleware signature and the chain
A middleware function has three arguments.
function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next();
}
app.use(logger);
The req is the request object. The res is the response object. The next is a function that passes control to the next middleware. If the middleware does not call next() and does not send a response, the request hangs.
Middleware can be applied globally with app.use(), to a path prefix with app.use('/api', mw), or to a specific route with app.get('/path', mw, handler).
app.use(logger);
app.use('/api', apiLogger);
app.get('/users', requireAuth, listUsers);
The chain is built in registration order. A request passes through each middleware in the order it was registered, until one of them sends a response or calls next() with an error.
app.use((req, res, next) => {
console.log('First');
next();
});
app.use((req, res, next) => {
console.log('Second');
next();
});
app.get('/', (req, res) => {
console.log('Handler');
res.send('Hello');
});
A request to / logs First, Second, Handler, and then sends the response. The order is deterministic.
Middleware can modify the request and response. A middleware that parses the body adds req.body. A middleware that sets a header adds to the response. A middleware that loads a user adds req.user.
function loadUser(req, res, next) {
req.user = { id: 1, name: 'Alice' };
next();
}
app.use(loadUser);
app.get('/me', (req, res) => {
res.json(req.user);
});
The req.user is available in every handler that runs after the middleware. This is how middleware shares data with handlers.
A middleware can end the request-response cycle by sending a response. When it does, the chain stops.
function requireAuth(req, res, next) {
if (!req.headers.authorization) {
return res.status(401).send('Unauthorized');
}
next();
}
If the middleware sends the response, the handler does not run. If it calls next(), the chain continues.
b. Error-handling middleware and async middleware
An error-handling middleware has four arguments.
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something broke!' });
});
The four arguments distinguish it from a regular middleware. Express recognizes the arity and treats the function as an error handler. The error handler must be registered after all other middleware and routes.
Errors reach the error handler through next(err) or through a thrown exception in a synchronous handler.
app.get('/error', (req, res) => {
throw new Error('Synchronous error');
});
app.get('/next-error', (req, res, next) => {
next(new Error('Passed to next'));
});
Both errors are caught by the error handler. Express catches synchronous exceptions in handlers and passes them to next() automatically. Asynchronous exceptions are not caught in Express 4.
// Express 4: not caught
app.get('/async-error', async (req, res) => {
throw new Error('Async error'); // unhandled rejection
});
In Express 4, an async handler must catch its own errors and pass them to next().
app.get('/async', async (req, res, next) => {
try {
const data = await fetchData();
res.json(data);
} catch (err) {
next(err);
}
});
In Express 5, a rejected promise is passed to next() automatically.
// Express 5
app.get('/async', async (req, res) => {
const data = await fetchData(); // rejection goes to error handler
res.json(data);
});
An error handler can pass the error to the next error handler by calling next(err).
app.use((err, req, res, next) => {
if (err.type === 'validation') {
return res.status(400).json({ error: err.message });
}
next(err); // pass to the next error handler
});
app.use((err, req, res, next) => {
res.status(500).json({ error: 'Internal error' });
});
The first error handler handles validation errors. For other errors, it calls next(err), which passes the error to the second handler. This is how specialized error handlers are composed.
The default error handler is Express’s built-in. It sends the error stack in development and a generic message in production. A custom error handler replaces it.
c. Writing custom middleware
A custom middleware is a function with the (req, res, next) signature. The patterns are as varied as the concerns they address.
Request logging.
function requestLogger(req, res, next) {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
console.log(`${req.method} ${req.url} ${res.statusCode} ${duration}ms`);
});
next();
}
app.use(requestLogger);
The middleware records the start time, registers a listener on the response’s finish event, and calls next(). When the response is sent, the listener logs the method, URL, status, and duration.
Header setting.
function securityHeaders(req, res, next) {
res.set('X-Content-Type-Options', 'nosniff');
res.set('X-Frame-Options', 'DENY');
res.set('Referrer-Policy', 'no-referrer');
next();
}
app.use(securityHeaders);
The middleware sets security headers on every response. The helmet package does this more comprehensively, but the pattern is the same.
Authentication.
function authenticate(req, res, next) {
const token = req.headers.authorization?.slice(7);
if (!token) {
return res.status(401).json({ error: 'Missing token' });
}
try {
req.user = verifyToken(token);
next();
} catch (err) {
res.status(401).json({ error: 'Invalid token' });
}
}
app.use('/api', authenticate);
The middleware extracts the token from the Authorization header, verifies it, and attaches the user to the request. If the token is missing or invalid, it sends a 401 and does not call next().
Validation.
function validateBody(schema) {
return (req, res, next) => {
const { error } = schema.validate(req.body);
if (error) {
return res.status(400).json({ error: error.message });
}
next();
};
}
app.post('/users', validateBody(userSchema), createUser);
The validateBody function returns a middleware. It is a middleware factory: a function that takes configuration and returns a middleware. This is how middleware is parameterized.
Rate limiting.
function rateLimit(maxRequests, windowMs) {
const requests = new Map();
return (req, res, next) => {
const ip = req.ip;
const now = Date.now();
const windowStart = now - windowMs;
const timestamps = (requests.get(ip) || []).filter((t) => t > windowStart);
if (timestamps.length >= maxRequests) {
return res.status(429).json({ error: 'Too many requests' });
}
timestamps.push(now);
requests.set(ip, timestamps);
next();
};
}
app.use('/api', rateLimit(100, 60000));
The rateLimit function returns a middleware that tracks request timestamps per IP address and rejects requests that exceed the limit.
Async middleware.
function loadUserFromDb(req, res, next) {
User.findById(req.params.id)
.then((user) => {
if (!user) return res.status(404).json({ error: 'Not found' });
req.user = user;
next();
})
.catch(next);
}
app.get('/users/:id', loadUserFromDb, (req, res) => {
res.json(req.user);
});
The middleware returns a promise. The .catch(next) passes any rejection to the error handler. This is the Express 4 pattern for async middleware.
The middleware factory pattern is the standard way to parameterize middleware. A function that takes configuration and returns a middleware is more flexible than a middleware that reads configuration from a global variable.
function requireRole(role) {
return (req, res, next) => {
if (!req.user) {
return res.status(401).json({ error: 'Not authenticated' });
}
if (req.user.role !== role) {
return res.status(403).json({ error: 'Forbidden' });
}
next();
};
}
app.get('/admin', requireRole('admin'), adminHandler);
The requireRole function returns a middleware that checks the user’s role. The role is the parameter, and the middleware is the returned function.
Complete Example Session
// ============================================
// PART 1: BASIC MIDDLEWARE
// ============================================
const express = require('express');
const app = express();
function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next();
}
app.use(logger);
// ============================================
// PART 2: MIDDLEWARE CHAIN
// ============================================
app.use((req, res, next) => {
console.log('First');
next();
});
app.use((req, res, next) => {
console.log('Second');
next();
});
app.get('/', (req, res) => {
console.log('Handler');
res.send('Hello');
});
// ============================================
// PART 3: MODIFYING THE REQUEST
// ============================================
function loadUser(req, res, next) {
req.user = { id: 1, name: 'Alice' };
next();
}
app.use(loadUser);
app.get('/me', (req, res) => {
res.json(req.user);
});
// ============================================
// PART 4: ENDING THE RESPONSE
// ============================================
function requireAuth(req, res, next) {
if (!req.headers.authorization) {
return res.status(401).send('Unauthorized');
}
next();
}
app.get('/protected', requireAuth, (req, res) => {
res.send('Protected');
});
// ============================================
// PART 5: ERROR HANDLING MIDDLEWARE
// ============================================
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something broke!' });
});
// ============================================
// PART 6: ASYNC MIDDLEWARE (EXPRESS 4)
// ============================================
app.get('/async', async (req, res, next) => {
try {
const data = await fetchData();
res.json(data);
} catch (err) {
next(err);
}
});
// ============================================
// PART 7: ASYNC MIDDLEWARE (EXPRESS 5)
// ============================================
app.get('/async', async (req, res) => {
const data = await fetchData();
res.json(data);
});
// ============================================
// PART 8: MULTIPLE ERROR HANDLERS
// ============================================
app.use((err, req, res, next) => {
if (err.type === 'validation') {
return res.status(400).json({ error: err.message });
}
next(err);
});
app.use((err, req, res, next) => {
res.status(500).json({ error: 'Internal error' });
});
// ============================================
// PART 9: MIDDLEWARE FACTORY
// ============================================
function validateBody(schema) {
return (req, res, next) => {
const { error } = schema.validate(req.body);
if (error) {
return res.status(400).json({ error: error.message });
}
next();
};
}
app.post('/users', validateBody(userSchema), createUser);
// ============================================
// PART 10: RATE LIMITING MIDDLEWARE
// ============================================
function rateLimit(maxRequests, windowMs) {
const requests = new Map();
return (req, res, next) => {
const ip = req.ip;
const now = Date.now();
const timestamps = (requests.get(ip) || []).filter((t) => t > now - windowMs);
if (timestamps.length >= maxRequests) {
return res.status(429).json({ error: 'Too many requests' });
}
timestamps.push(now);
requests.set(ip, timestamps);
next();
};
}
app.use('/api', rateLimit(100, 60000));
The ten parts covered basic middleware, the chain, modifying the request, ending the response, error handling, async middleware in Express 4, async middleware in Express 5, multiple error handlers, middleware factories, and rate limiting.
Quick Reference
Middleware Signatures
| Type | Signature | Purpose |
|---|---|---|
| Regular | (req, res, next) | Runs before handlers |
| Error | (err, req, res, next) | Handles errors |
| Factory | (config) => (req, res, next) | Parameterized middleware |
Middleware Registration
| Method | Scope |
|---|---|
app.use(mw) | All routes |
app.use('/path', mw) | Path prefix |
app.get('/path', mw, handler) | Specific route |
router.use(mw) | Router scope |
Error Propagation
| Trigger | Result |
|---|---|
next() | Next middleware |
next(err) | Next error handler |
throw in sync handler | Error handler |
| Async rejection (Express 5) | Error handler |
| Async rejection (Express 4) | Unhandled |
Common Patterns
| Pattern | Purpose |
|---|---|
| Logger | Log requests |
| Auth | Verify identity |
| Validation | Check input |
| Rate limit | Throttle requests |
| Headers | Set security headers |
| Error handler | Format errors |
Best Practices
✅ Do This:
// Call next() to pass control
function mw(req, res, next) {
console.log('hi');
next();
} // ✅
// Use four arguments for error handlers
app.use((err, req, res, next) => { }); // ✅
// Register error handlers last
app.use(errorHandler); // ✅
// Use try/catch in async middleware (Express 4)
app.get('/async', async (req, res, next) => {
try { /* ... */ } catch (err) { next(err); }
}); // ✅
// Use factories for parameterized middleware
function requireRole(role) {
return (req, res, next) => { /* ... */ };
} // ✅
// Attach data to req for downstream handlers
req.user = user;
next(); // ✅
// End the response when the middleware fails
if (!auth) return res.status(401).send('Unauthorized'); // ✅
❌ Don’t Do This:
// Don't forget to call next()
function mw(req, res, next) {
console.log('hi'); // request hangs
} // ❌
// Don't use three arguments for an error handler
app.use((err, req, res) => { }); // treated as regular // ❌
// Don't register error handlers before routes
app.use(errorHandler);
app.get('/route', handler); // error handler never reached // ❌
// Don't throw in async middleware (Express 4)
app.get('/async', async (req, res) => {
throw new Error('Unhandled');
}); // ❌
// Don't call next() after sending a response
res.send('done');
next(); // error // ❌
// Don't modify the response after it is sent
res.send('first');
res.send('second'); // error // ❌
// Don't use a global for middleware configuration
const role = 'admin'; // use a factory instead // ⚠️
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Request hangs | Middleware did not call next() | Call next() |
| Error handler not called | Fewer than four arguments | Use (err, req, res, next) |
| Error handler not reached | Registered before routes | Move to the end |
| Async error unhandled | Express 4 does not catch | try/catch with next(err) |
next() after response | Called after res.send() | Return after sending |
| Data not available | Middleware registered after route | Register before |
| Middleware runs everywhere | Used app.use instead of route | Scope with path or route |
Real-World Examples
1. Request Logger
function logger(req, res, next) {
const start = Date.now();
res.on('finish', () => {
console.log(`${req.method} ${req.url} ${res.statusCode} ${Date.now() - start}ms`);
});
next();
}
2. Auth Middleware
function requireAuth(req, res, next) {
if (!req.headers.authorization) {
return res.status(401).json({ error: 'Unauthorized' });
}
next();
}
3. Role Check
function requireRole(role) {
return (req, res, next) => {
if (req.user?.role !== role) {
return res.status(403).json({ error: 'Forbidden' });
}
next();
};
}
4. Request ID
function requestId(req, res, next) {
req.id = crypto.randomUUID();
res.set('X-Request-Id', req.id);
next();
}
5. CORS
function cors(req, res, next) {
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') return res.sendStatus(204);
next();
}
6. Security Headers
function securityHeaders(req, res, next) {
res.set('X-Content-Type-Options', 'nosniff');
res.set('X-Frame-Options', 'DENY');
next();
}
7. Body Validation
function validateBody(schema) {
return (req, res, next) => {
const { error } = schema.validate(req.body);
if (error) return res.status(400).json({ error: error.message });
next();
};
}
8. Rate Limiting
function rateLimit(max, windowMs) {
const hits = new Map();
return (req, res, next) => {
const now = Date.now();
const list = (hits.get(req.ip) || []).filter((t) => t > now - windowMs);
if (list.length >= max) return res.status(429).send('Too many requests');
list.push(now);
hits.set(req.ip, list);
next();
};
}
9. Error Handler
app.use((err, req, res, next) => {
console.error(err);
res.status(err.status || 500).json({ error: err.message });
});
10. Async Wrapper
function asyncHandler(fn) {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
}
app.get('/async', asyncHandler(async (req, res) => {
const data = await fetchData();
res.json(data);
}));
Visual
Middleware Chain
┌─────────────────────────────────────────────────────────────┐
│ REQUEST │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ logger (req, res, next) → next() │ │
│ └─────────────────────┬───────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ express.json() (req, res, next) → next() │ │
│ └─────────────────────┬───────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ requireAuth (req, res, next) → next() │ │
│ └─────────────────────┬───────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Route Handler (req, res) → res.send() │ │
│ └─────────────────────┬───────────────────────────────┘ │
│ │ │
│ ▼ │
│ RESPONSE │
│ │
└─────────────────────────────────────────────────────────────┘
Error Propagation
┌─────────────────────────────────────────────────────────────┐
│ NORMAL FLOW │
│ │
│ mw1 → mw2 → mw3 → handler → response │
│ │
├─────────────────────────────────────────────────────────────┤
│ │
│ ERROR FLOW (next(err)) │
│ │
│ mw1 → mw2 → next(err) ────────┐ │
│ │ │
│ ▼ │
│ mw3 SKIPPED │
│ handler SKIPPED │
│ │ │
│ ▼ │
│ errorHandler1 → errorHandler2 → response │
│ │
│ Regular middleware is skipped. │
│ Error handlers run in order. │
│ │
└─────────────────────────────────────────────────────────────┘
Middleware Factory
┌─────────────────────────────────────────────────────────────┐
│ function requireRole(role) { │
│ return (req, res, next) => { │
│ if (req.user?.role !== role) { │
│ return res.status(403).send('Forbidden'); │
│ } │
│ next(); │
│ }; │
│ } │
│ │
│ requireRole('admin') ──▶ returns middleware │
│ requireRole('user') ──▶ returns middleware │
│ │
│ Each call creates a new middleware with the parameter │
│ captured in the closure. │
│ │
└─────────────────────────────────────────────────────────────┘
Express 4 vs Express 5 Async
┌─────────────────────────────────────────────────────────────┐
│ EXPRESS 4 │
│ │
│ app.get('/async', async (req, res, next) => { │
│ try { │
│ const data = await fetchData(); │
│ res.json(data); │
│ } catch (err) { │
│ next(err); │
│ } │
│ }); │
│ │
│ Manual try/catch required. │
│ │
├─────────────────────────────────────────────────────────────┤
│ │
│ EXPRESS 5 │
│ │
│ app.get('/async', async (req, res) => { │
│ const data = await fetchData(); │
│ res.json(data); │
│ }); │
│ │
│ Rejection is passed to next() automatically. │
│ │
└─────────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Middleware signature | (req, res, next) |
| Error handler signature | (err, req, res, next) |
| Global registration | app.use(mw) |
| Path registration | app.use('/path', mw) |
| Route registration | app.get('/path', mw, handler) |
| Pass control | next() |
| Pass error | next(err) |
| Error handler order | After all routes |
| Async (Express 4) | try/catch + next(err) |
| Async (Express 5) | Automatic |
| Factory pattern | (config) => (req, res, next) |
Key takeaways:
- A middleware is a function with
(req, res, next). It can read or modify the request and response, end the cycle by sending a response, or pass control by callingnext(). Middleware runs in the order it is registered. - An error handler has four arguments:
(err, req, res, next). Express distinguishes it by arity. It is called whennext(err)is invoked or when a synchronous handler throws. It must be registered after all other middleware and routes. - Errors skip regular middleware and jump to the error handler. When
next(err)is called, Express skips all regular middleware and passes the error to the next error handler. This is how errors propagate through the chain. - Async middleware requires
try/catchin Express 4. A rejected promise is not caught by Express 4. The middleware must catch the error and callnext(err). Express 5 catches rejections automatically. - Middleware factories parameterize middleware. A function that takes configuration and returns a middleware is the standard pattern for middleware that needs parameters.
requireRole('admin')returns a middleware that checks for the admin role. - Middleware can attach data to the request.
req.user,req.session, andreq.bodyare set by middleware and read by handlers. The data is available only to middleware and handlers that run after the middleware that set it. - Order matters. A body parser must run before a handler that reads
req.body. An auth middleware must run before a route that requires a user. An error handler must run after every route. The order is the application’s responsibility.
Remember: Middleware is the architecture of an Express application. It is not a feature of the framework; it is the framework. The application is a chain of functions, each with the same signature, each passing control to the next. The chain is built in registration order. Errors travel through a separate chain of error handlers. Async middleware returns a promise, and the framework’s handling of that promise depends on the Express version. Custom middleware is a function. Parameterized middleware is a function that returns a function. Data shared with handlers is attached to the request. Understand the chain, the order, and the error path, and the rest of Express is a library of middleware and a set of routing conveniences on top of the same mechanism.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!