Lifecycle Hooks
Fine-grained callbacks at various stages of a request
Overview
Hooks are arrays of callbacks executed serially at specific points in the request lifecycle. Unlike middleware, hooks are simpler callbacks that don't wrap the fetch call.
const client = createClient(api, {
hooks: {
beforeRequest: [
(req) => {
req.init.headers = {
...req.init.headers as Record<string, string>,
'X-Request-Id': crypto.randomUUID(),
};
}
],
afterResponse: [
(req, res) => {
console.log(`${req.init.method} ${req.url} → ${res.status}`);
}
],
beforeError: [
(error) => {
console.error('Request failed:', error.message);
return error;
}
],
},
});Hook Reference
| Hook | When | Can Modify |
|---|---|---|
beforeRequest | Before the fetch call | Request headers, body, URL |
afterResponse | After a successful response | Return a new Response to replace |
beforeRetry | Between retry attempts | Logging only |
beforeError | Before an error is thrown | Return a transformed WebError |