Skip to content
Download

Precedence

When multiple routes can match the same request, Mach uses route precedence to choose the most specific match.

Static route segments always take precedence over route parameters.

For example:

app.mapGet("/users/profile", [] {
return mach::ok("Profile");
});
app.mapGet("/users/{name:string}", [](mach::Context& context) {
const auto name = context.request.routeParam("name");
return mach::ok(name);
});

For this request:

GET /users/profile

Mach selects:

/users/profile

rather than:

/users/{name:string}

This allows specific routes and dynamic routes to coexist naturally.

When constrained parameters overlap, more specific constraints take precedence.

The int constraint takes precedence over the string constraint.

For example:

app.mapGet("/users/{name:string}", [](mach::Context& context) {
const auto name = context.request.routeParam("name");
return mach::ok(name);
});
app.mapGet("/users/{id:int}", [](mach::Context& context) {
const int id = context.request.routeParam<int>("id");
return mach::ok(id);
});

For:

GET /users/42

Mach selects:

/users/{id:int}

For:

GET /users/alice

Mach selects:

/users/{name:string}

Mach rejects route definitions that are ambiguous with an already registered route.

For example, these routes describe the same integer route shape:

/users/{id:int}
/users/{number:int}

The parameter names are different, but both routes match the same requests. Registering both for the same HTTP method results in an invalid route definition.

Mach also rejects other route definitions whose matching behavior would be ambiguous.

This keeps route selection deterministic and prevents registration order from being used to resolve fundamentally ambiguous route definitions.

When matching a request, the important precedence rules are:

  1. Static segments take precedence over parameter segments.
  2. int parameters take precedence over string parameters.
  3. Ambiguous route definitions are rejected when routes are registered.

You’ve now covered Mach’s routing system: defining routes, using parameters and constraints, and understanding how routes are matched.