Middleware

This document explains Azu's middleware system, called handlers, and how they enable cross-cutting concerns.

What is Middleware?

Middleware are components that process requests before and after your endpoint logic. They form a chain through which every request passes:

Request → Handler 1 → Handler 2 → Handler 3 → Endpoint

Response ← Handler 1 ← Handler 2 ← Handler 3 ← Response

The Handler Pattern

In Azu, middleware are called "handlers" and extend Azu::Handler::Base:

class MyHandler < Azu::Handler::Base
  def call(context)
    # Before request processing
    call_next(context)
    # After request processing
  end
end

The call_next Pattern

call_next(context) passes control to the next handler:

Output for a request:

Handler Chain

Handlers execute in registration order:

For a request:

  1. Rescuer wraps everything in error handling

  2. Logger records start time

  3. Auth checks credentials

  4. Rate limiter checks quota

  5. Endpoint handles request

  6. Rate limiter continues

  7. Auth continues

  8. Logger logs duration

  9. Rescuer returns response

Use Cases

Cross-Cutting Concerns

Handlers are ideal for concerns that span multiple endpoints:

Concern
Handler

Error handling

Rescuer

Logging

Logger

Authentication

AuthHandler

Rate limiting

RateLimitHandler

CORS

CorsHandler

Compression

CompressionHandler

Caching

CacheHandler

Request Modification

Add or modify request data:

Response Modification

Modify response after endpoint:

Short-Circuiting

Stop processing early:

Handler vs Endpoint

When to Use Handlers

  • Applies to multiple routes

  • Cross-cutting concern

  • Modifies request/response metadata

  • Need to wrap endpoint execution

When to Use Endpoints

  • Specific business logic

  • Single route

  • Main request handling

  • Produces the response body

Handler Composition

Conditional Handlers

Apply logic conditionally:

Handler with State

Handlers can maintain state (use carefully):

Configurable Handlers

Accept configuration in constructor:

Ordering Best Practices

Recommended handler order:

Error Handling

The Rescuer handler catches exceptions:

Always place Rescuer first so it catches errors from all handlers.

Testing Handlers

Test handlers in isolation:

See Also

Last updated

Was this helpful?