FrontendPro

87Implement request and response interceptors similar to Axios

mediumAbout 45 minutesCodingfetchpromisesmiddlewareauth

Problem

Implement createHttpClient({ baseURL = "", fetch: fetchImpl = window.fetch }), a small Axios-style client on top of fetch:

  • client.request(config), where config is { url, method = "GET", headers = {}, data }, plus shortcuts client.get(url, config) and client.post(url, data, config).
  • Requests go to baseURL + url. data is sent as JSON with content-type: application/json.
  • The result is { data, status, headers, config }, where data is parsed JSON (or text if the body is not JSON).
  • A status outside 200–299 rejects with an Error that has error.response (the same shape) and error.config.
  • client.interceptors.request.use(onFulfilled, onRejected) and client.interceptors.response.use(onFulfilled, onRejected) register interceptors and return an id; .eject(id) removes one.

Order, like Axios: request interceptors run in reverse order of registration (the last one added runs first), response interceptors in registration order. Each may return a value or a promise. A response onRejected can recover, for example by refreshing a token and returning client.request(error.config).

const api = createHttpClient({ baseURL: "https://api.example.com" });
api.interceptors.request.use((config) => ({ ...config, headers: { ...config.headers, authorization: `Bearer ${getToken()}` } }));
api.interceptors.response.use(undefined, async (error) => {
  if (error.response?.status === 401 && !error.config.retried) {
    await refreshToken();
    return api.request({ ...error.config, retried: true });
  }
  throw error;
});
const { data } = await api.get("/me");

Try it yourself

Write your solution, run it, then submit to check it against the tests.

App.jsxReact + DOM

Step-by-step

Each manager stores { id, onFulfilled, onRejected } entries in an array, with use returning a new id and eject(id) removing that entry. Keep removed entries out of future chains only.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever