TypeScript

JSON POST Helper

admin by @admin ADMIN
3d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Companion to `http<T>` — POST a JSON body and parse a JSON response, both typed. Handles the boilerplate Content-Type header and JSON serialization.
TypeScript
Raw
export async function postJson<TReq, TRes>(
  url: string,
  body: TReq,
  opts: Omit<RequestInit, 'method' | 'body'> = {},
): Promise<TRes> {
  const r = await fetch(url, {
    method: 'POST',
    body: JSON.stringify(body),
    ...opts,
    headers: {
      'Content-Type': 'application/json',
      'Accept':       'application/json',
      ...(opts.headers ?? {}),
    },
  });
  if (!r.ok) throw new Error(`HTTP ${r.status}: ${await r.text()}`);
  return r.json() as Promise<TRes>;
}

type CreateUser  = { name: string; email: string };
type CreatedUser = { id: number; name: string; email: string; created_at: string };

const u = await postJson<CreateUser, CreatedUser>('/api/users', { name: 'Alice', email: 'a@x.com' });
Tags

Save your own code snippets

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