SyntaxStudy
Sign Up
JavaScript Building a Fetch Wrapper
JavaScript Intermediate 5 min read

Building a Fetch Wrapper

Fetch Interceptor Pattern

Build a thin wrapper around fetch to add auth tokens, base URLs, retry logic, and response normalisation in one place.

Example
const BASE = "https://api.example.com";
async function api(path, opts = {}) {
  const headers = { "Content-Type": "application/json", ...opts.headers };
  const token = localStorage.getItem("token");
  if (token) headers.Authorization = `Bearer ${token}`;
  const res = await fetch(BASE + path, { ...opts, headers });
  if (res.status === 401) { logout(); return; }
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}
export const get = (path) => api(path);
export const post = (path, body) => api(path, { method: "POST", body: JSON.stringify(body) });
Pro Tip

A thin API wrapper reduces boilerplate and centralises authentication logic.