pre-alpha

GuidesEndpoints

Add middleware

implemented Updated November 20, 2026 2 min read

A middleware runs around an action. It is Hinoki's own typed interface, so it behaves the same on Kiso and on Granian: you do not wrap the ASGI application, and an application served by Kiso can use it.

# notes/middleware.py
from hinoki.http import Middleware, MiddlewareRequest, Next, Response


class Tenant(Middleware):
    async def __call__(self, request: MiddlewareRequest, call_next: Next) -> Response:
        if "x-tenant" not in request.headers:
            return Response(400, "missing x-tenant", content_type="text/plain")
        response = await call_next()
        return response.with_header("x-served-by", "tenant")

Declare it on an action, or for the whole application:

# notes/main.py
from hinoki import Hinoki, http

from .middleware import Tenant


@http.get("/items")
async def items() -> list[str]:
    return []


app = Hinoki(include=[items], middleware=[Tenant()])

RouteGroup actions take the same option. The application's middleware runs first, then the action's, in the order listed; each one returns what the next one returned unless it answers itself.

What a middleware sees

MiddlewareRequest is the head of the request: method, path, the matched route template in route (for example /items/{item_id}, safe to use as a metrics label), lower-case headers, the raw query string, client, scheme and request_id. It has no body and cannot change the request.

call_next() returns a Response with the action's answer. An error the action raised is already an HTTP answer, and an atomic=True transaction is already rolled back, so a middleware that reads the database after call_next() sees the state after the rollback. Call call_next() at most once (a second call is a 500). A middleware that raises is translated like an action error; one that returns anything but a Response is a 500.

Security, CORS and request-id headers are added after the middleware returns.

Order and what stays outside

  1. Hinoki answers what needs no action first: the ready check, request size limits, host, CORS preflight and HTTPS redirect policies, the startup probe and the documentation pages.
  2. The route is chosen. An unknown path (404) or method (405) never reaches a middleware.
  3. The application's middleware, then the action's.
  4. Authentication, rate limit, negotiation, body binding, the transaction and the handler.

execution.request_timeout applies to the whole of it: when it expires the 504 is produced outside the middleware, which only sees the cancellation.

Cost

An action with middleware is served by Python for the whole request, so it leaves the native lane: hinoki routes --lanes shows lane_reason middleware. Actions without middleware keep their lane. A middleware that only needs to observe requests can use the access log instead, which does not change the lane.

Errors and edge cases

  • A middleware must have async def __call__; any other object is a TypeError when the application or the action is declared.
  • Keep a middleware free of request state kept in globals: use the MiddlewareRequest it receives.

See also