Create Custom Middleware

This guide shows you how to create custom middleware handlers in Azu.

Basic Handler

Create a handler by extending Azu::Handler::Base:

class TimingHandler < Azu::Handler::Base
  def call(context)
    start = Time.instant

    call_next(context)

    duration = Time.instant - start
    context.response.headers["X-Response-Time"] = "#{duration.total_milliseconds.round(2)}ms"
  end
end

Register the Handler

Add your handler to the application pipeline:

MyApp.start [
  TimingHandler.new,          # First in chain
  Azu::Handler::Rescuer.new,
  Azu::Handler::Logger.new,
  # ... endpoints
]

Authentication Handler

CORS Handler

Rate Limiting Handler

Request ID Handler

Compression Handler

Conditional Handler

Skip handler based on conditions:

Handler Ordering

Order matters - handlers execute in sequence:

See Also

Last updated

Was this helpful?