Express.js middleware patterns and implementation
View on GitHubplugins/aai-stack-express/skills/express-middleware/SKILL.md
February 1, 2026
Select agents to install to:
npx add-skill https://github.com/the-answerai/alphaagent-team/blob/main/plugins/aai-stack-express/skills/express-middleware/SKILL.md -a claude-code --skill express-middlewareInstallation paths:
.claude/skills/express-middleware/# Express Middleware Skill
Patterns for creating and using middleware in Express.js.
## Middleware Basics
### Middleware Structure
```typescript
import { Request, Response, NextFunction } from 'express'
// Basic middleware
function middleware(req: Request, res: Response, next: NextFunction) {
// Do something
next() // Pass to next middleware
}
// Middleware with error
function middlewareWithError(req: Request, res: Response, next: NextFunction) {
if (!req.headers.authorization) {
return next(new Error('No authorization header'))
}
next()
}
// Async middleware
async function asyncMiddleware(req: Request, res: Response, next: NextFunction) {
try {
const data = await fetchSomething()
req.data = data
next()
} catch (error) {
next(error)
}
}
```
### Middleware Order
```typescript
import express from 'express'
const app = express()
// Order matters! Middleware runs top to bottom
// 1. Body parsing (run early)
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
// 2. Logging (run early)
app.use(morgan('dev'))
// 3. Security headers
app.use(helmet())
// 4. CORS
app.use(cors())
// 5. Authentication (before routes)
app.use(authenticate)
// 6. Routes
app.use('/api', routes)
// 7. 404 handler (after routes)
app.use(notFoundHandler)
// 8. Error handler (last)
app.use(errorHandler)
```
## Request Processing
### Request Logging
```typescript
function requestLogger(req: Request, res: Response, next: NextFunction) {
const start = Date.now()
// Log on response finish
res.on('finish', () => {
const duration = Date.now() - start
console.log({
method: req.method,
path: req.path,
status: res.statusCode,
duration: `${duration}ms`,
ip: req.ip,
})
})
next()
}
```
### Request ID
```typescript
import { v4 as uuid } from 'uuid'
function requestId(req: Request, res: Response, next: NextFunction) {
const id = req.headers['x-request-id'] || uuid()
req.id = id