Middleware overview¶
Baldr ships a set of middleware — cross-cutting components that intercept every request. They run in registration order on the way in and reverse order on the way out; see Middleware for details.
Shipped middleware¶
The middleware headers are header-only and re-exported through <Baldr/Baldr.hpp>. Each page documents its options struct.
| Middleware | Purpose | Page |
|---|---|---|
LoggingMiddleware |
Logs every request and response with elapsed microseconds | Logging |
RequestIdMiddleware |
Echoes or generates X-Request-ID for log correlation |
Request ID |
ExceptionHandlerMiddleware |
Maps thrown exceptions to a 500 response | Exception handler |
CompressionMiddleware |
gzip-encodes eligible response bodies | Compression |
SecurityHeadersMiddleware |
Sets X-Content-Type-Options, X-Frame-Options, HSTS, COOP/CORP, etc. | Security headers |
CorsMiddleware |
CORS headers + OPTIONS preflight short-circuit |
CORS |
CsrfMiddleware |
Double-submit cookie CSRF protection | CSRF |
RateLimitMiddleware |
Rejects clients that exceed a configured rate | Rate limit |
Recommended pipeline order¶
Outer-most first, inner-most (closest to the handler) last. This matches the order in Middleware:
src/main.cpp
app.Use<RequestIdMiddleware>()
.Use<ExceptionHandlerMiddleware>()
.Use<LoggingMiddleware>()
.Use<CompressionMiddleware>()
.Use<SecurityHeadersMiddleware>()
.Use<CorsMiddleware>()
.Use<CsrfMiddleware>()
.Use<RateLimitMiddleware>();
Writing your own¶
Any class that implements IMiddleware can be added to the pipeline:
- Implement
IMiddleware. - Register the implementation with the service collection (typically
AddTransient<T>()). - Add the middleware with
app.Use<T>()(orapp->Use<T>()on askr::Arc<WebApplication>—Use<T>()returnsconst WebApplication&, so use.chaining for fluent configuration).
See the Middleware usage page for a complete walkthrough.