Skip to content

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:

  1. Use next() to continue the chain and pass control to the next middleware
  2. Use return to stop the chain and prevent events from firing
  3. Use throw to 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:

  1. Use next() to mark the error as handled and continue with the main middleware chain
  2. Use next(error) to forward the original (or transformed) error to the next error handler
  3. Use return to end error handling and stop the middleware chain
  4. Use throw to raise a new error to be caught by the error chain

Next steps