Skip to content

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:

bash
Guard ➔ Validator ➔ Interceptor ➔ Route Handler

Applying a Guard (--@Guard) ​

To protect an endpoint, add the --@Guard(...) attribute comment directly above your route function:

luau
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 Profile

You can also chain multiple rules inside a single Guard:

luau
--@Guard(Auth, Admin)
function Profile.Delete(req: IRequest)
    return response.json({ message = "User deleted" })
end

Rule 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:

luau
-- 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 with 401 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:

luau
-- 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 Admin

When 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 ​

ActionHow To Do ItResult
Apply GuardWrite --@Guard(RuleName) above handlerRuns src/guards/RuleName.luau
Allow RequestReturn true in guard ruleRequest proceeds to next rule/handler
Deny (Default)Return false in guard ruleHalts request with 401 Unauthorized
Deny (Custom)Throw error(exception.Forbidden("..."))Halts request with specified status code & message