TypeScript

Bearer-Auth Fetch Wrapper

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Wrap fetch so every request automatically attaches an Authorization: Bearer header from a token getter. Token can be a static string or a function (useful for refreshing).
TypeScript
Raw
export function authedFetch(tokenSource: string | (() => string | Promise<string>)) {
  return async (url: string, opts: RequestInit = {}): Promise<Response> => {
    const token = typeof tokenSource === 'function' ? await tokenSource() : tokenSource;
    return fetch(url, {
      ...opts,
      headers: {
        ...(opts.headers ?? {}),
        Authorization: `Bearer ${token}`,
      },
    });
  };
}

const api = authedFetch(() => localStorage.getItem('access_token') ?? '');

const r = await api('/api/me');
const r2 = await api('/api/profile', { method: 'PUT', body: JSON.stringify(profile) });
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.