Skip to content

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.

Registered with app:use, they run for every request:

app:use(function(req, res, next)
print(req.method .. " " .. req.path)
next()
end)

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" })
end
end
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)

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 first
end)
local reports = app:group("/reports")
reports:use(auth)
reports:get("/daily", handler)

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.