Middleware Ordering
Middleware executes in the order in which it is registered on the way into the request pipeline.
When control returns from the endpoint, execution continues through the middleware in reverse order.
Registration Order
Section titled “Registration Order”Consider two middleware registrations:
mach::AppBuilder builder;
builder.use<FirstMiddleware>();builder.use<SecondMiddleware>();
auto app = builder.build();For a matching request, the execution order is:
FirstMiddleware beforeSecondMiddleware beforeEndpointSecondMiddleware afterFirstMiddleware afterThe first registered middleware therefore wraps everything registered after it.
Why Order Matters
Section titled “Why Order Matters”Middleware order can affect application behavior.
For example, if one middleware adds information that another middleware expects to read, the producer must run first on the way into the pipeline.
Similarly, a middleware registered earlier can inspect or modify the response after later middleware and the endpoint have completed.
class FirstMiddleware {public: void invoke(mach::Context& context, mach::Next& next) { // Runs first
next();
// Runs last }};
class SecondMiddleware {public: void invoke(mach::Context& context, mach::Next& next) { // Runs second
next();
// Runs before FirstMiddleware finishes }};Short-Circuiting and Order
Section titled “Short-Circuiting and Order”Ordering also matters when middleware can short-circuit the pipeline.
For example:
builder.use<LoggingMiddleware>();builder.use<SecurityMiddleware>();If SecurityMiddleware stops the request without calling next(), the endpoint is skipped.
However, control still returns to LoggingMiddleware, so any code after its next() call can still run.
Conceptually:
LoggingMiddleware beforeSecurityMiddlewareSecurityMiddleware short-circuitsLoggingMiddleware afterMiddleware registered after the short-circuiting middleware is never reached.
Choosing an Order
Section titled “Choosing an Order”A useful way to think about ordering is that earlier middleware forms an outer layer around later middleware.
First Second Third EndpointChoose the order based on which behavior should happen earlier on the request path and later on the response path.
You’ve now covered Mach’s middleware pipeline: creating middleware, registering it, continuing or short-circuiting requests, and controlling execution order.