Patterns for designing and implementing Express middleware
View on GitHubplugins/aai-dev-backend/skills/middleware-patterns/SKILL.md
February 1, 2026
Select agents to install to:
npx add-skill https://github.com/the-answerai/alphaagent-team/blob/main/plugins/aai-dev-backend/skills/middleware-patterns/SKILL.md -a claude-code --skill middleware-patternsInstallation paths:
.claude/skills/middleware-patterns/# Middleware Patterns Skill
Patterns for designing reusable middleware in Express applications.
## Middleware Basics
```typescript
import { Request, Response, NextFunction } from 'express';
// Basic middleware signature
type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
// Middleware types
// 1. Application-level: app.use(middleware)
// 2. Router-level: router.use(middleware)
// 3. Route-level: app.get('/path', middleware, handler)
// 4. Error-handling: (err, req, res, next) => {}
```
## Common Middleware Patterns
### Request Logging
```typescript
function requestLogger(options: { level?: string } = {}) {
return (req: Request, res: Response, next: NextFunction) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
logger.log({
level: options.level || 'info',
method: req.method,
path: req.path,
statusCode: res.statusCode,
duration: `${duration}ms`,
userAgent: req.get('user-agent'),
});
});
next();
};
}
app.use(requestLogger());
```
### Request ID
```typescript
import { v4 as uuid } from 'uuid';
function requestId() {
return (req: Request, res: Response, next: NextFunction) => {
const id = req.headers['x-request-id'] as string || uuid();
req.id = id;
res.setHeader('X-Request-ID', id);
next();
};
}
// Extend Request type
declare global {
namespace Express {
interface Request {
id: string;
}
}
}
```
### Response Time
```typescript
function responseTime() {
return (req: Request, res: Response, next: NextFunction) => {
const start = process.hrtime();
res.on('finish', () => {
const [seconds, nanoseconds] = process.hrtime(start);
const ms = seconds * 1000 + nanoseconds / 1000000;
res.setHeader('X-Response-Time', `${ms.toFixed(2)}ms`);
});
next();
};
}
```
### Validation Middleware
```typescript
import { z } from 'z