Router → Constraints

Constraints

Wrap a Lua pattern in () after a param name to restrict which segment values the route will match. The pattern is anchored — the entire segment must match for the route to be selected.

Inline constraint syntax

The full form for a constrained, typed param is: :name(pattern)=type. Each part is optional except :name.

FormWhat it does
:id(%d+)Segment must match %d+ — captured as string
:id(%d+)=numberMust match %d+, then coerced to number
:action(%a+)Segment must be letters only — captured as string
:slug(%w[%w%-]+)Alphanumeric with hyphens — captured as string

Examples

-- digits only, raw string
app:Get("user/:id(%d+)", function(req, res)
    print(req.params.id)  -- "123" — string
end)

-- digits only, coerced to number
app:Get("user/:id(%d+)=number", function(req, res)
    print(req.params.id)  -- 123 — number
end)

-- lowercase letters only
app:Get("cmd/:action(%a+)", function(req, res)
    print(req.params.action)  -- "fire", "reload" | rejects "fire2"
end)

-- page number: digits, returned as integer
app:Get("page/:n(%d+)=int", function(req, res)
    res:Send({ page = req.params.n })
end)

Common Lua pattern classes

ClassMatches
%dAny digit (0–9)
%aAny letter (A–Z, a–z)
%wAny alphanumeric (letter or digit)
%lLowercase letter
%uUppercase letter
%pPunctuation
.Any character

See the Lua 5.1 pattern reference for the full specification.

Non-match behaviour

When a segment does not satisfy the constraint pattern, the route is skipped entirely — it results in a 404, not a 400. The next route in priority order is tried. This is different from type coercion failure (see below).

Constraint vs coercion failure. A constraint mismatch (pattern not satisfied) skips the route silently and continues matching. A coercion failure (pattern matched but =type conversion failed) triggers OnParamError or responds 400 automatically.

Interaction with OnParamError

OnParamError is called only when a segment satisfies the Lua pattern but the =type coercion step fails. Use it to customise the error response.

app:OnParamError(function(req, res, paramName, value)
    res:Status(422):Send({
        error = "Cannot coerce param '" .. paramName .. "': " .. tostring(value)
    })
end)

See also

← Router  ·  Named Params | full type annotation list  ·  Wildcards & Globs | unnamed captures  ·  App | OnParamError handler