Goal
Run one or more middleware functions before an HTTP handler executes. Middleware can inspect the request and either continue to the handler or short-circuit with a response.How It Works
Middleware in iii is just a regular function. The engine calls it before the handler. The function returns either{ action: "continue" } to proceed, or { action: "respond", response: {...} } to short-circuit.
There are two ways to attach middleware:
| Type | Where to configure | Scope | Runs |
|---|---|---|---|
| Per-route | Trigger config (middleware_function_ids) | Specific endpoint | After condition check |
| Global | iii-config.yaml (rest_api.middleware) | All HTTP endpoints | Before condition check |
Per-Route Middleware
1. Register the middleware function
Middleware functions receive a request object withpath_params, query_params, headers, and method (no body).
- Node / TypeScript
- Python
auth-middleware.ts
2. Attach middleware to the trigger
Includemiddleware_function_ids in the trigger config. Middleware runs in the order listed.
- Node / TypeScript
- Python
auth-middleware.ts (continued)
3. Test it
Chaining Multiple Middleware
List multiple function IDs. They execute in order. If any short-circuits, the rest are skipped.Global Middleware
Global middleware runs on every HTTP request, before route-level conditions and per-route middleware. Configure it iniii-config.yaml:
iii-config.yaml
Middleware Response Protocol
Every middleware function must return one of:Middleware Input
Middleware receives a lightweight request object (no body, for performance):Middleware does not receive the request body. This is intentional: global middleware runs before body parsing, so auth checks and rate limiting skip the expensive JSON parse for rejected requests. Use conditions for body-based validation.
Request Lifecycle
Error Handling
| Scenario | Engine behavior |
|---|---|
Middleware returns { action: "continue" } | Proceeds to next middleware or handler |
Middleware returns { action: "respond", response } | Returns the response, skips handler |
| Middleware returns invalid action | Logs warning, treats as continue |
| Middleware returns no result | Logs warning, treats as continue |
| Middleware throws an error | Returns 500 with error ID for debugging |
| Middleware exceeds timeout | Returns 504 Gateway Timeout |