CodShot
TypeScript Public

Typed JSON Fetch Helper

Wrap fetch with JSON parsing, typed responses, and useful HTTP error messages.

#typescript #fetch #api #json
TypeScript
type ApiErrorBody = {
  message?: string;
};

export async function fetchJson<T>(
  input: RequestInfo | URL,
  init?: RequestInit,
): Promise<T> {
  const response = await fetch(input, {
    ...init,
    headers: {
      Accept: 'application/json',
      ...init?.headers,
    },
  });

  const contentType = response.headers.get('content-type') ?? '';
  const isJson = contentType.includes('application/json');

  const body = isJson
    ? await response.json()
    : null;

  if (!response.ok) {
    const errorBody = body as ApiErrorBody | null;

    throw new Error(
      errorBody?.message
      ?? `Request failed with status ${response.status}.`,
    );
  }

  return body as T;
}

Snippet actions

CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0
Forks
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support