Middleware Overview
In Apion, middleware is just a Handler — there’s no separate middleware type. A middleware handler typically returns Continue(modifiedRequest) to pass control to the next handler, but can also return Complete, Fail, or Skip.
Applying Middleware
Section titled “Applying Middleware”Global
Section titled “Global”Applies to all requests:
server .use(LoggingMiddleware()) .use(CorsMiddleware())Path-Scoped
Section titled “Path-Scoped”Applies only to routes matching the prefix:
server.use("/api", authMiddleware)Router-Scoped
Section titled “Router-Scoped”Applies only within a router:
val adminRouter = Router() .use(requireAdmin) .get("/dashboard", dashboardHandler)
server.use("/admin", adminRouter)Route-Level
Section titled “Route-Level”Chain handlers for a specific route:
server.get("/protected", authMiddleware, handler)Middleware Patterns
Section titled “Middleware Patterns”Modify the Request
Section titled “Modify the Request”Add data to the context for downstream handlers:
val withUser: Handler = request => { val user = lookupUser(request.params("id")) Future.successful(Continue( request.copy(context = request.context + ("user" -> user)) ))}Short-Circuit
Section titled “Short-Circuit”Return a response immediately, stopping the chain:
val requireAuth: Handler = request => request.header("authorization") match { case Some(_) => Future.successful(Continue(request)) case None => "Unauthorized".asText(401) }Transform the Response
Section titled “Transform the Response”Use finalizers to modify the response after a handler completes:
val addHeader: Handler = request => { val finalizer: Finalizer = (_, response) => Future.successful(response.copy( headers = response.headers.add("X-Custom", "value") )) Future.successful(Continue(request.addFinalizer(finalizer)))}Execution Order
Section titled “Execution Order”- Global middleware runs in registration order
- Path-scoped middleware runs if the path matches
- Route handlers run if the method and path match
- Finalizers run in LIFO order on the response
Built-in Middleware
Section titled “Built-in Middleware”| Middleware | Purpose |
|---|---|
AuthMiddleware | JWT authentication with RBAC |
CorsMiddleware | Cross-origin resource sharing |
SecurityMiddleware | Security headers |
LoggingMiddleware | Request/response logging |
CompressionMiddleware | Response compression |
StaticMiddleware | Static file serving |
CookieMiddleware | Cookie management |
RateLimiterMiddleware | Request throttling |
FileUploadMiddleware | Multipart file uploads |
BodyLimitMiddleware | Request body size limits |