Overview
Middleware in Framefox allows you to process HTTP requests and responses at various stages. Middleware can modify requests, add headers, handle authentication, log activity, and more.Middleware System
Framefox’s middleware system provides:- Request/Response Processing: Intercept and modify HTTP traffic
- Ordering Control: Execute middleware in specific sequence
- Built-in Middleware: Pre-configured common functionality
- Custom Middleware: Easy creation of your own middleware
Built-in Middleware
Framefox includes several built-in middleware components:- ProfilerMiddleware: Performance profiling and debugging
- ExceptionMiddleware: Centralized exception handling
- RequestMiddleware: Request context management
- EntityManagerMiddleware: Database session handling
- CsrfMiddleware: CSRF token management
- FirewallMiddleware: Security rules and IP filtering
- SessionMiddleware: Session management
- CustomCORSMiddleware: CORS headers
Middleware Execution Order
Middleware executes in a specific order:Creating Custom Middleware
Basic Middleware
Create middleware using Starlette’sBaseHTTPMiddleware:
Middleware with Dependencies
Access services from the container:Middleware with Configuration
Use settings for configuration:Registering Middleware
Application-Level
Add middleware to your FastAPI application:In MiddlewareManager
Extend theMiddlewareManager for centralized configuration:
Middleware Examples
Authentication Middleware
Request ID Middleware
Caching Middleware
Session Middleware
Framefox’s built-inSessionMiddleware manages user sessions:
- Automatic Management: Session created and updated automatically
- Signed Cookies: Sessions signed for security
- Expiration: Configurable timeout with
cookie_max_agesetting - Cleanup: Expired sessions automatically removed
CSRF Middleware
TheCsrfMiddleware protects against CSRF attacks:
Best Practices
- Order Matters: Register middleware in the correct order
- Performance: Keep middleware fast; avoid heavy operations
- Error Handling: Handle exceptions gracefully
- State Management: Use
request.statefor request-scoped data - Testing: Test middleware independently
- Documentation: Document middleware behavior and configuration