Skip to main content
Use middleware when you need to wrap execution for a request. Use a plugin when you want to bundle middleware, hooks, tools, resources, or prompts into one reusable unit. If the behavior is analytics, logging, or metrics that should happen after the response is already written, prefer onAfterResponse(...) inside the plugin over onAfterHandle(...).

Build middleware first when the behavior is request-scoped

Middleware is the fastest path when you want to:
  • block or allow execution
  • decorate ctx
  • time calls
  • wrap next()

Build a plugin when you want a reusable package of behavior

definePlugin(...) is the cleanest path when you want to share behavior across multiple servers.

A plugin can ship more than middleware

A plugin can register:
  • middleware
  • hooks
  • tools
  • resources
  • prompts

Rule of thumb

  • choose middleware for one request-layer behavior
  • choose a plugin when you want a reusable bundle
  • use definePlugin(...) when you want a stable, publishable plugin API

See also