Fetch Interceptor Pattern
Build a thin wrapper around fetch to add auth tokens, base URLs, retry logic, and response normalisation in one place.
Build a thin wrapper around fetch to add auth tokens, base URLs, retry logic, and response normalisation in one place.
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) });
A thin API wrapper reduces boilerplate and centralises authentication logic.
More in JavaScript