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

HookWhenCan Modify
beforeRequestBefore the fetch callRequest headers, body, URL
afterResponseAfter a successful responseReturn a new Response to replace
beforeRetryBetween retry attemptsLogging only
beforeErrorBefore an error is thrownReturn a transformed WebError