Skip to content

Interceptor ​

An Interceptor wraps around your route handler, giving you control before the request reaches the handler and after the handler returns a response. This makes interceptors perfect for logging, timing execution speed, and transforming outgoing response payloads.

Interceptors execute right before your route handler:

bash
Guard ➔ Validator ➔ Interceptor ➔ Route Handler

Applying an Interceptor (--@Interceptor) ​

To attach an interceptor to an endpoint, add the --@Interceptor(...) attribute comment directly above your route handler function:

luau
local common = require("common")
local response = common.response

local Home = {}

--@Interceptor(Transform)
function Home.Get(req: IRequest)
    return response.json({ message = "Hello from Mayari!" })
end

return Home

You can also apply multiple interceptor rules in sequence:

luau
--@Interceptor(Logger, Transform)
function Home.Get(req: IRequest)
    return response.json({ message = "Hello from Mayari!" })
end

Execution Sequence: Multiple interceptors run in order from left to right.

Writing Interceptor Rules (src/interceptors/) ​

Interceptor rule files must be placed inside src/interceptors/ (e.g., --@Interceptor(Logger) resolves to src/interceptors/Logger.luau).

Each rule file exports a single function that receives req and next:

luau
-- src/interceptors/Logger.luau
local function Logger(req: IRequest, next: INext)
    local start = os.clock()

    -- Pass control down to the next interceptor or route handler
    next()

    local elapsed = (os.clock() - start) * 1000
    print(`[{req.method}] {req.path} - Completed in {elapsed} ms`)
end

return Logger

The Onion Pattern & Response Transformation ​

Because Interceptors follow the Onion Pattern, calling next() executes the rest of the pipeline and returns the handler's outgoing response.

You can inspect, mutate, or completely replace the response object before it gets sent back to the client:

luau
-- src/interceptors/Transform.luau
local common = require("common")
local response = common.response

local function Transform(req: IRequest, next: INext)
    local res = next()

    -- Mutate response or wrap payload in a standardized format
    return response.json({
        success = true,
        data = res.body,
        timestamp = os.time()
    }, res.config)
end

return Transform

Cheat Sheet ​

FeatureUsage / Detail
Attribute Syntax--@Interceptor(RuleName)
Rule PathMust live in src/interceptors/RuleName.luau
Signaturefunction Rule(req: IRequest, next: INext)
Calling next()Required to continue down the chain to the route handler
Response OverrideReturn a new response payload to modify what the client receives