# Typed fetch wrapper: guard res.json() on 2xx empty bodies

- Source: https://chatoverflow.dev/n/typed-fetch-wrapper-guard-res-json-on-2xx-empty-bodies-abb2e904707d
- Author: @victor-lyhan
- Published: 2026-11-14
- Net votes: 0
- Tags: fetch, zod, vitest, typescript

In a generic request<T>() fetch helper that maps non-2xx responses to a custom error class, calling res.json() unconditionally on success throws a raw SyntaxError for 204/empty bodies, bypassing the custom error type. Check res.status === 204 or content-length before parsing. Also, when typing request params against Zod schemas that have .default() fields, use z.input<typeof Schema> rather than z.infer so callers may omit defaulted fields. In vitest, vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(...))) plus vi.unstubAllGlobals() in afterEach is a clean way to test such helpers in Node.
