Kest

Search

Search the documentation

Introduction

Interceptors

Wrap a handler: run code before and after, change the result, or answer from a cache.

An interceptor wraps the call to your handler, like a sleeve around it. It can do something before, call next.handle() to run the handler, and then do something after with the result. It can also decide not to call the handler at all (answer from a cache) or change what comes back.

Loading diagram…

It is the NestJS interceptor in plain Kotlin: no Observable, no operators.

Write one

@Injectable
class TimingInterceptor : Interceptor {
    private val log = Logger("Timing")
 
    override suspend fun intercept(ctx: ExecutionContext, next: CallHandler): Any? {
        val started = System.nanoTime()
        try { return next.handle() }                                                       // call the handler
        finally { log.log("${ctx.request.method} ${ctx.request.path} took ${(System.nanoTime() - started) / 1_000_000} ms") }
    }
}
 
@Controller("/orders") @UseInterceptors(TimingInterceptor::class)
class OrdersController { ... }

Four things interceptors are good at

1. Timing and logging (above).

2. Changing the result (every response in the same envelope):

@Injectable class Envelope : Interceptor {
    override suspend fun intercept(ctx: ExecutionContext, next: CallHandler): Any? =
        mapOf("data" to next.handle(), "servedAt" to Instant.now().toString())
}

3. Answering without the handler (a cache):

override suspend fun intercept(ctx: ExecutionContext, next: CallHandler): Any? {
    val key = ctx.request.path
    cache[key]?.let { return it }                 // hit: the handler never runs
    return next.handle().also { cache[key] = it } // miss: run it and remember
}

4. Converting errors or adding a safety net (a timeout, a retry): try { next.handle() } catch (e: Exception) { ... }.

Built in

InterceptorWhat it does
LoggingInterceptorlogs method, path, status and time
TimeoutInterceptor(millis)answers 408 if the handler takes longer (one shared timer for all requests)
CacheInterceptoranswers GETs from the cache (Caching)
ClassSerializerInterceptorapplies @Exclude, @Expose, @Transform (Serialization)

Attach and order

@UseInterceptors(A::class, B::class)        // on a controller or a handler
app.http(adapter) { useInterceptors(Timing::class) }      // every route

The first one listed is the outermost: it runs first on the way in and last on the way out. Global interceptors wrap controller ones, which wrap handler ones.

To make your own annotation apply an interceptor (@Cached(ttl = 60)), use @Intercepted: see Custom decorators.

Interceptor, middleware or guard?

An interceptor knows the route and its annotations and sees the handler's result (an object, before it becomes JSON), which middleware does not. It runs after guards, so it only sees allowed requests. Use a guard to refuse, an interceptor to measure or reshape.

Testing

Call intercept(ctx) { fakeCallHandler } with a handler that returns a known value and assert what the interceptor returns; or call the endpoint with TestServer and check the final response.

Read more