AgentSkillsCN

middleware-guide

中间件组织模式(认证、上下文、校验、错误边界)。关键词:中间件、Express 中间件、认证、错误边界、请求上下文。

SKILL.md
--- frontmatter
name: middleware-guide
description: "Middleware organization patterns (auth, context, validation, error boundaries). Keywords: middleware, express middleware, auth, error boundary, request context."

Middleware Guide

This skill explains how to structure and apply Express middleware safely and consistently.


Types of middleware

  • Auth: authenticates identity and attaches it to the request context
  • Authorization: enforces permissions/roles
  • Validation: validates input and short-circuits on invalid requests
  • Context: attaches correlation ids, request metadata, and logging context
  • Error boundary: catches errors and converts them into consistent responses

Recommended structure

text
src/middleware/
  auth.ts
  authorization.ts
  request_context.ts
  validation.ts
  error_boundary.ts

Error boundary pattern

Ensure async errors are captured:

ts
export function asyncHandler(fn) {
  return (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
}

Register error middleware last:

ts
app.use("/api", routes);
app.use(errorBoundary); // last

Related Skills

  • architecture-overview
  • async-and-errors