Guard
Guards protect your routes by running authorization checks before a request reaches your handler. If a Guard passes, the request continues down the pipeline. If it fails, Mayari immediately halts execution and returns an error response.
Guards are always the first attribute to run:
Guard ➔ Validator ➔ Interceptor ➔ Route HandlerApplying a Guard (--@Guard)
To protect an endpoint, add the --@Guard(...) attribute comment directly above your route function:
local common = require("common")
local response = common.response
local Profile = {}
--@Guard(Auth)
function Profile.Get(req: IRequest)
return response.json({ message = "Welcome to your profile!" })
end
return ProfileYou can also chain multiple rules inside a single Guard:
--@Guard(Auth, Admin)
function Profile.Delete(req: IRequest)
return response.json({ message = "User deleted" })
endRule Order: Multiple guard rules execute from left to right. If any rule fails, execution stops immediately.
Writing Guard Rules (src/guards/)
All Guard rules must be stored in src/guards/. The file name matches the rule name passed to the attribute (e.g., Auth maps to src/guards/Auth.luau).
Each file exports a single function that receives the req object and returns a boolean:
-- src/guards/Auth.luau
local function Auth(req: IRequest): boolean
local token = req.headers["authorization"]
-- Return true to allow the request, or false to block it
return token == "Bearer secret-token"
end
return Auth- Returns
true: Request is allowed and moves to the next step. - Returns
false: Mayari automatically halts the request and responds with401 Unauthorized.
Custom Error Responses & Exceptions
If returning false (which defaults to 401 Unauthorized) isn't descriptive enough, you can throw a custom exception using common.exception with Luau's error() function:
-- src/guards/Admin.luau
local common = require("common")
local exception = common.exception
local function Admin(req: IRequest): boolean
local role = req.headers["x-user-role"]
if role ~= "admin" then
-- Throws a 403 Forbidden exception with a custom message
error(exception.Forbidden("Requires administrator privileges"))
end
return true
end
return AdminWhen error() is called with a Mayari exception, Mayari catches it, stops processing the request, and sends back the matching HTTP status code and error payload.
Cheat Sheet
| Action | How To Do It | Result |
|---|---|---|
| Apply Guard | Write --@Guard(RuleName) above handler | Runs src/guards/RuleName.luau |
| Allow Request | Return true in guard rule | Request proceeds to next rule/handler |
| Deny (Default) | Return false in guard rule | Halts request with 401 Unauthorized |
| Deny (Custom) | Throw error(exception.Forbidden("...")) | Halts request with specified status code & message |