Skip to content

Overview

Register before, after, and finally hooks on host.http and route groups - pipeline order, short-circuiting, and state provisioning.

AI generated, pending review Updated 10 days ago · Flare 0.3

Middleware is request-scoped logic that runs around route handlers. Register it globally on host.http (use, before, after, finally) or inside a route group with the same APIs on the group builder.

Flare supports two authoring styles:

Controllers have no middleware slot. Register hooks on the arc or group so they compile into the route pipeline.

HookRunsShort-circuit
beforeBefore the route handlerReturn a non-undefined override (typically new FlareResponse(…)) to skip the handler and all after hooks. finally still runs.
afterOnly when the handler ranReturn a non-undefined override to replace result. Later after hooks still run.
finallyAlways after the handler path or error dispatchUncommon override to replace the outgoing value

Route and query contract values validate before before middleware. JSON body validation runs after before, immediately before the handler.

For a route inside a non-isolated group:

  • before: global hooks (registration order) → group hooks → handler
  • after: global hooks → group hooks
  • finally: group hooks (reverse order within group), then global hooks (reverse order)
Group APIBehavior
g.isolated()Skip all global middleware for routes in this group
g.exclude([Cls])Drop specific global middleware classes from this group
g.replace(from, to)Swap one global middleware class for another

Route { isolated: true } skips middleware for that route only.

The alternative this replaces is onion middleware: a stack of functions that each call the next and wrap the rest in a try/finally. Whether your cleanup runs there depends on the layers around it. A middleware that short-circuits without calling next, or one that throws before control reaches your finally, can skip it, and “does finally run after a handler error” turns into per-framework trivia you learn by being burned. Flare fixes the order at build(): finally hooks always run, on the normal path, on a before() override that short-circuits the handler, and after an error is dispatched. A throwing error handler is contained the same way, logged and skipped so the chain continues and the original error stays the one the client sees.

Middleware before() hooks can provides request state tokens that downstream routes declare in state. Throws inside middleware are handled by error handlers the same way as handler throws.

CORS preflight is not middleware. It runs in the method-dispatch layer before the pipeline. See CORS.