Skip to content
Download

Understanding Middleware

Middleware runs around endpoint execution and lets you apply behavior to HTTP requests as they move through a Mach application.

It is useful for concerns that should apply across multiple endpoints, such as logging, request validation, security checks, or response processing.

When a request reaches a Mach application, it passes through the registered middleware pipeline before reaching the matched endpoint.

Each middleware can:

  • inspect or modify the current request
  • inspect or modify the current response
  • continue to the next step in the pipeline
  • stop the pipeline and produce a response immediately

Conceptually, the flow looks like this:

Request
↓
Middleware A
↓
Middleware B
↓
Endpoint
↓
Middleware B
↓
Middleware A
↓
Response

Middleware therefore runs both before and after the next step in the pipeline, depending on where its logic is placed.

A middleware can perform work before continuing:

// Before the next middleware or endpoint
next();
// After the next middleware or endpoint

This makes middleware useful for behavior that surrounds request handling.

For example, a logging middleware could record when a request starts, continue the pipeline, and then record the final response status.

Middleware normally continues processing by invoking the next step in the pipeline.

If it does not continue, later middleware and the matched endpoint are not executed.

This is called short-circuiting the pipeline and is useful when a request should be handled immediately, such as when a required condition is not satisfied.

Short-circuiting is covered in detail later in this section.

Middleware executes in the order in which it is registered on the way into the pipeline.

After the endpoint runs, control returns through the middleware in reverse order.

For example, with:

Middleware A
Middleware B
Endpoint

the execution order is:

A before
B before
Endpoint
B after
A after

Because of this, registration order can affect application behavior.

Middleware is a good fit for behavior that applies across multiple endpoints or needs to run as part of the request pipeline.

Typical examples include:

  • request and response logging
  • authentication or authorization checks
  • CORS handling
  • CSRF protection
  • exception handling
  • request preprocessing
  • response headers or other shared response behavior

Endpoint-specific business logic generally belongs in the endpoint itself rather than in middleware.

Middleware works with both minimal APIs and controllers.

The middleware pipeline is independent of how the matched endpoint is defined, so the same middleware can apply to endpoints created with app.mapGet(), controllers, and other route mappings.


Next, you’ll learn how to create a custom middleware in Mach.