Handlers

Handlers provide middleware functionality for Azu applications, allowing you to process requests and responses at different stages of the request lifecycle.

Built-in Handlers

Azu::Handler::Rescuer

Handles exceptions and provides error responses.

Azu.start [
  Azu::Handler::Rescuer.new
]

Features:

  • Automatic exception handling

  • Development-friendly error pages

  • Production-safe error responses

  • Stack trace logging in development

Azu::Handler::Logger

Provides request/response logging.

Azu.start [
  Azu::Handler::Logger.new
]

Features:

  • Request method and path logging

  • Response status and timing

  • Error logging

  • Configurable log levels

Azu::Handler::CORS

Handles Cross-Origin Resource Sharing (CORS) headers.

Configuration:

  • origins - Allowed origins

  • methods - Allowed HTTP methods

  • headers - Allowed headers

  • credentials - Allow credentials

Azu::Handler::Static

Serves static files from a directory.

Configuration:

  • directory - Directory to serve files from

  • prefix - URL prefix for static files

  • index - Default file to serve for directories

Azu::Handler::CSRF

Provides CSRF protection for state-changing operations.

Features:

  • Automatic token generation

  • Token validation

  • Configurable token header

  • Session-based token storage

Custom Handlers

Create custom handlers by inheriting from Azu::Handler::Base.

Basic Handler

Handler with Configuration

Handler with State

Handler Lifecycle

Handlers are executed in the order they are added to the middleware stack.

Request Phase

Error Handling

Handler Registration

Application Level

Endpoint Level

Handler Configuration

Environment-based Configuration

Conditional Handlers

Handler Testing

Unit Testing

Integration Testing

Performance Considerations

Handler Order

Order handlers by their processing requirements:

  1. Security handlers (CORS, CSRF)

  2. Logging handlers (Logger)

  3. Business logic handlers (Custom)

  4. Error handlers (Rescuer)

Handler Efficiency

Common Patterns

Authentication Handler

Rate Limiting Handler

Caching Handler

Next Steps

Last updated

Was this helpful?