Introduction
Middleware
Code that runs for every request, before routing.
Middleware is a function that sits in front of your routes. Every request passes through it on the way in, and every response on the way out. Use it for things that apply to all requests and have nothing to do with a particular endpoint: giving each request an id, logging, compression, CORS, security headers.
Middleware sees every request, including ones that match no route (404s) and CORS preflights. It decides whether to continue by calling next(request), or stops the request by returning a response itself.
Write one
class RequestId : Middleware {
override suspend fun handle(request: HttpRequest, next: suspend (HttpRequest) -> HttpResponse): HttpResponse {
val id = request.header("x-request-id") ?: UUID.randomUUID().toString()
return next(request).withHeader("x-request-id", id) // continue, then add a header to the response
}
}
app.http(NettyHttpAdapter(8080)) {
useMiddleware(RequestId()) // every route
useMiddleware(AuditLog::class, forRoutes = listOf("/api/**"), exclude = listOf("/api/health")) // only some routes; created by the container
}Three things a middleware can do:
// 1. pass information to the rest of the pipeline (guards and handlers read it from request.attributes)
request.attributes["tenant"] = tenantOf(request)
return next(request)
// 2. change the response afterwards
return next(request).withHeader("cache-control", "no-store")
// 3. answer by itself and stop (a maintenance page, a block list, a cache hit)
if (request.path.startsWith("/admin") && request.remoteAddress !in allowed) return HttpResponse(403)Choosing the routes
forRoutesandexcludetake paths with*(exactly one segment) and**(any depth):"/api/**"is everything under/api,"/users/*"is one level.methods = listOf(HttpMethod.POST)limits by HTTP method.- Order matters: middleware runs in the order you register it, the first one outermost.
Built in
Common needs are one-liners (each is middleware underneath):
| Helper | Does |
|---|---|
enableCors(...) | CORS headers and preflight answers |
useCompression() | gzip large responses |
useSecurityHeaders { } | the usual security headers |
useSession { } / useCsrf { } | sessions and CSRF protection |
serveStatic(prefix, dir) | files from a directory |
useRequestContext { } | values that follow the request (Async local storage) |
useMetrics(), useTracing(...) | measure and trace every request |
A middleware that never blocks can be declared nonBlocking = true, so @NonBlocking routes can stay on the I/O thread.
Middleware, guard, interceptor: which one?
| Middleware | Guard | Interceptor | |
|---|---|---|---|
| runs | first, before routing | after routing | around the handler |
| knows the route and its annotations | no | yes | yes |
| sees the handler's result | the final response | no | yes, the returned object |
| typical use | request id, CORS, compression, logging | may this caller do this? | timing, caching, mapping results |
Rule of thumb: if it must also work for a URL that does not exist, or has nothing to do with what the endpoint does, use middleware. If it depends on the endpoint (@Roles("admin")), use a guard.
Testing
A middleware is a plain class: call handle(request) { HttpResponse(200) } with a fake next and assert the response, or start a test server with Testing.createModule and call it for real.