Middlewares
A middleware is a function (req, res, next). The chain only advances when
next() is called — not calling it halts the request, express-style.
Global middlewares
Section titled “Global middlewares”Registered with app:use, they run for every request:
app:use(function(req, res, next) print(req.method .. " " .. req.path) next()end)Per-route middlewares
Section titled “Per-route middlewares”Pass a single function — or a list — before the handler:
local function auth(req, res, next) if req.headers["authorization"] then next() else res:status(401):json({ error = "Unauthorized" }) endend
app:get("/private", auth, function(req, res) res:send("secret")end)
app:get("/very-private", { auth, audit }, function(req, res) res:send("very secret")end)Group middlewares
Section titled “Group middlewares”A route group takes a middleware list
between the prefix and the callback; it runs before every route in the
group. group:use adds one for the routes registered after the call:
app:group("/admin", { auth }, function(admin) admin:get("/stats", handler) -- auth runs firstend)
local reports = app:group("/reports")reports:use(auth)reports:get("/daily", handler)Execution order
Section titled “Execution order”A middleware that responds without calling next() short-circuits the chain
— the handler never runs. That is how the auth example above rejects
unauthenticated requests.
