Skip to content
Download

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.

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 before
SecondMiddleware before
Endpoint
SecondMiddleware after
FirstMiddleware after

The first registered middleware therefore wraps everything registered after it.

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
}
};

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 before
SecurityMiddleware
SecurityMiddleware short-circuits
LoggingMiddleware after

Middleware registered after the short-circuiting middleware is never reached.

A useful way to think about ordering is that earlier middleware forms an outer layer around later middleware.

First
Second
Third
Endpoint

Choose 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.