Overview
Dioxus fullstack is built on Axum, giving you access to the full Tower middleware ecosystem. You can apply middleware:- Per-route - Using the
#[middleware]attribute on server functions - Router-level - Using Axum’s
.layer()method on the router - Custom extractors - Creating reusable extractors for common patterns
Per-Route Middleware
Apply middleware to specific server functions using the#[middleware] attribute:
Multiple Middleware Layers
Stack multiple middleware by adding multiple attributes:Router-Level Middleware
Apply middleware to all routes using Axum’s.layer() method:
Common Middleware Layers
Authentication Middleware
Custom Auth Extractor
Create a reusable authentication extractor:Session-Based Auth
Use cookies for session management:Rate Limiting
Limit request rates usingtower-governor:
CORS Configuration
Configure Cross-Origin Resource Sharing:Request Logging
Log all requests:State Injection
Share state across your application:examples/07-fullstack/server_state.rs for more details.
Error Handling
Handle errors in middleware:Compression
Compress responses to reduce bandwidth:Request ID Tracking
Add unique IDs to each request:Security Headers
Add security headers:Timeout
Timeout long-running requests:Custom Middleware
Create your own middleware:Middleware Order
Middleware executes in order:- logging → 2. auth → 3. rate_limit → handler → 3. rate_limit → 2. auth → 1. logging
Best Practices
- Use per-route middleware for endpoint-specific concerns
- Use router-level middleware for cross-cutting concerns (logging, CORS)
- Put auth early in the middleware chain
- Add timeouts to prevent hanging requests
- Log request IDs for debugging
- Validate early - reject bad requests before they reach handlers
- Use typed extractors instead of manually parsing headers
- Consider performance - middleware runs on every request
Examples
examples/07-fullstack/middleware.rs- Basic middleware usageexamples/07-fullstack/auth/- Authentication exampleexamples/07-fullstack/server_state.rs- State and extractorsexamples/07-fullstack/custom_axum_serve.rs- Custom server setup