Core concepts

Interceptors

Change every request and response in one place.

Before a request

onRequest runs before each try, retries included, so a refreshed token is picked up on the next attempt. Return the request to send.

ts
const api = createClient({  baseUrl: "https://api.example.com",  onRequest: async (request) => {    const token = await session.token();    request.headers.set("Authorization", `Bearer ${token}`);    return request;  },});

After a response

onResponse sees the raw Response before Tempo parses it. Throw to turn a success into a failure.

ts
onResponse: (response, request) => {  metrics.timing("api", performance.now() - request.startedAt);  return response;},

Order

Pass an array to run several in order. Request interceptors run first to last, response interceptors last to first, like layers around the call.

Was this page helpful?

Updated