Skip to content

Middleware ​

Middleware functions sit between incoming client requests and your route handlers. They let you inspect, modify, or block requests before they hit your code, as well as transform responses on the way out.

Common uses include:

  • Authentication & Authorization
  • Request Body & Parameter Validation
  • Logging & Analytics
  • Global Headers & CORS

How Middleware Works (The Onion Pattern) ​

In Mayari, middleware uses the Onion Pattern. Every middleware receives two parameters:

  1. req — The incoming request object.
  2. next — A function that passes control down the chain to the next middleware or route handler.

When you call next(), execution dives deeper into the pipeline. Once the route handler completes, execution bubbles back up, running any code written after next():

luau
local function loggerMiddleware(req: IRequest, next: INext)
    print(`1. Request incoming: {req.method} {req.path}`)

    next() -- Passes control down the chain

    print("2. Response sent back to client")
end

Global Middleware ​

Global middleware runs on every request sent to your server. Pass an array of middleware functions as the second argument when instantiating Mayari in src/main.luau:

lua
-- src/main.luau
local Mayari = require("mayari")

local function logger(req: IRequest, next: INext)
    print(`[{req.method}] {req.path}`)
    next()
end

local function cors(req: IRequest, next: INext)
    local res = next()
    res.config.headers = res.config.headers or {}
    res.config.headers["Access-Control-Allow-Origin"] = "*"
end

-- Pass global middlewares array to Mayari.new()
local app = Mayari.new(8080, { logger, cors })

app:listen(function()
    print("Server running on port 8080")
end)

Route-Specific Middleware (Attributes) ​

For logic that only applies to specific endpoints, Mayari uses Attributes, a comment-based syntax declared directly above handler functions using --@:

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

local User = {}

--@Guard(Auth)
--@Validator(CreateUser)
--@Interceptor(Logger)
function User.Post(req: IRequest)
    return response.json({ message = "User created successfully" })
end

return User

Built-in Attributes & Directory Conventions ​

Attributes map directly to rule files located in specific directories under src/:

AttributeDirectoryPurpose
--@Guard(...)src/guards/Access control. Halts requests with 401 or custom exceptions if authorization fails.
--@Validator(...)src/validators/Schema validation. Checks body, params, or query and returns 400 if invalid.
--@Interceptor(...)src/interceptors/Request/Response wrappers. Useful for timing, logging, or response formatting.

Execution Pipeline Order ​

Regardless of the order you write your comments in, Mayari enforces a fixed execution sequence:

bash
Global Middlewares ➔ Guards ➔ Validators ➔ Interceptors ➔ Route Handler
  1. Global Middlewares run first in the order they were declared in Mayari.new().
  2. Guards evaluate access rules.
  3. Validators inspect request fields.
  4. Interceptors wrap the handler execution.
  5. Route Handler processes the request and returns data.

Key Rules & Best Practices ​

  • Call next(): Always call next() inside global middleware and interceptors, unless you are intentionally halting the request with an early response or exception.
  • Strict Directory Locations: Guard rules must live in src/guards/, validator rules in src/validators/, and interceptor rules in src/interceptors/.