While middleware wraps the entire request/response cycle, hooks let you tap into specific moments: before the request is handled, after the response is built, or when an error occurs.
let hooks = PrismHookRegistry()// Add a request ID to every requestawait hooks.onRequest { request in var req = request req.userInfo["requestId"] = UUID().uuidString return req}// Add timing header to every responseawait hooks.onResponse { request, response in var res = response res.headers.set(name: "X-Request-ID", value: request.userInfo["requestId"] ?? "") return res}// Log all errorsawait hooks.onError { error, request in print("Error on \(request.path): \(error)") return nil // Let default error handling take over}await server.use(PrismHooksMiddleware(registry: hooks))
Register multiple hooks of the same type — they run in order:
Hook Chain
await hooks.onResponse { req, res in var r = res r.headers.set(name: "X-Powered-By", value: "Prism") return r}await hooks.onResponse { req, res in var r = res r.headers.set(name: "X-Version", value: "4.4.0") return r}// Both headers are added to every response
Hooks are lighter than middleware when you only need to act at one specific point in the lifecycle. Use middleware when you need to wrap the entire request/response flow (e.g., timing, caching).