Overview
Middleware in xmcp allows you to intercept and process HTTP requests before they reach your MCP server endpoints. Use middleware for authentication, logging, rate limiting, and other cross-cutting concerns. xmcp supports two types of middleware:- Express Middleware - Traditional Express.js
RequestHandlerfunctions - Web Middleware - Modern async functions with MCP-specific context
Middleware Types
Express Middleware
Standard Express.js middleware pattern withreq, res, and next:
packages/xmcp/src/types/middleware.ts
Web Middleware
Modern async middleware with MCP authentication context:packages/xmcp/src/types/middleware.ts
Creating Custom Middleware
Create asrc/middleware.ts file in your project to define custom middleware.
Basic Express Middleware
examples/middlewares-custom/src/middleware.ts
Middleware Configuration
Middleware is automatically loaded fromsrc/middleware.ts when you run your xmcp server:
examples/middlewares-custom/xmcp.config.ts
Middleware Arrays
Compose multiple middleware functions by exporting an array:examples/middlewares-array/src/middleware.ts
next(), subsequent middleware and routes are not executed.
RequestHandlerAndRouter Type
For advanced use cases, combine middleware with Express routers:packages/xmcp/src/types/middleware.ts
Best Practices
Always Call next()
If you don’t send a response, call
next() to pass control to the next middlewareHandle Errors Gracefully
Always wrap auth logic in try-catch blocks and return appropriate HTTP status codes
Use Built-in Auth
For common auth patterns, use
apiKeyAuthMiddleware or jwtAuthMiddleware instead of custom codeKeep Middleware Focused
Each middleware should do one thing well. Compose multiple middleware for complex logic
Next Steps
Authentication
Learn about built-in authentication middleware
Transports
Configure HTTP and STDIO transports