Middleware support
Extend your agent with custom business logic using middleware. Compose cross-cutting behavior like routing, telemetry, rate limiting, analytics, and feature flags, or plug in your own.
Standard middleware
Middleware can be registered with agent.use either one at a time or as an array. They are executed in the order they were added.
Middleware functions receive a ctx (context) object and a next function. Normally, middleware calls next() to hand off control to the next one in the chain. However, middleware can also alter the flow in the following ways:
- Use
next()to continue the chain and pass control to the next middleware - Use
returnto stop the chain and prevent events from firing - Use
throwto trigger the error-handling middleware chain
Example
import { Agent, AgentMiddleware, filter } from '@xmtp/agent-sdk';
const onlyText: AgentMiddleware = async (ctx, next) => {
if (filter.isText(ctx.message)) {
// Continue to next middleware
await next();
}
// Break middleware chain
return;
};
const agent = await Agent.createFromEnv();
agent.use(onlyText);Error-handling middleware
Error middleware can be registered with agent.errors.use either one at a time or as an array. They are executed in the order they were added.
Error middleware receives the error, ctx, and a next function. Just like regular middleware, the flow in error middleware depends on how to use next:
- Use
next()to mark the error as handled and continue with the main middleware chain - Use
next(error)to forward the original (or transformed) error to the next error handler - Use
returnto end error handling and stop the middleware chain - Use
throwto raise a new error to be caught by the error chain
Next steps
- Explore message filters to process messages selectively
- Understand context and helpers for rich message handling

