How-to › Parse, validate and transform data

How to validate API responses at the SDK boundary with Zod#

Check each response a TypeScript SDK returns against a Zod schema of the fields callers use, so a renamed field or a truncated record fails at the call.

Audience
API consumer
Level
intermediate
Topic
Validate data shapes
Languages
TypeScript
Verified

The search endpoint renames version to latestVersion in one record and sends another record cut short. Your SDK casts the body to its response type and returns it, so the compiler is satisfied. Three layers later a template renders undefined as a version number, and the stack trace points at the template.

What you get

You will end up with an SDK method that checks its response against a schema before returning, and throws an error naming each failing path. This is for you if you call an API whose responses you do not control.

Short answer

Write a Zod schema for the fields your callers read, including every record inside a paginated envelope, and call safeParse on the decoded body before the SDK method returns. Throw an error that names each failing path. z.object strips keys you did not declare, so an added field passes. Valibot and Ajv report the same paths, and Valibot bundles to about a twentieth of Zod’s minified bytes.

You will need

Node 22 or later and an SDK method you can edit. Verified 2026-11-30 against Node 22.23.5, Zod 4.6.7, Valibot 1.5.0 and Ajv 8.20.0. The response body is one real answer from the npm registry’s search endpoint, recorded once by record.sh with email addresses and usernames removed, and served to the SDK from a loopback stand-in.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
Ajv with JSON SchemaThe API publishes JSON Schema or OpenAPI, and the schema should not be written twiceStops at the first error without allErrors, returns extra fields untouched, and ships a large run-time compilerYou write the schema by hand in TypeScript anyway
ValibotThe SDK ships to browsers and bundle bytes countEvery rule is a pipe of small functions, which reads longer than a method chainBundle size does not matter, and the team knows Zod
ZodA TypeScript SDK where the schema and the type should be one declarationAbout 16 times Valibot’s bytes, compressed, for this schema, and three and a half times that through import { z }The SDK runs in a browser, or a JSON Schema already exists

Zod and Valibot give the type and the check from one declaration and strip keys you did not declare. Ajv runs a schema you may already have from an OpenAPI document. Its run-time compiler bundles larger than Zod imported as a namespace, while its standalone output gzips smallest of all. Valibot is the smallest of the three libraries that build schemas at run time.

Write the schema for the fields callers read

Declare only the fields the SDK hands back, and declare the records inside the envelope as carefully as the envelope itself.

import * as z from 'zod'

// Only the fields the SDK hands to its callers. z.object strips every
// other key, so a field the API adds later passes and never leaks out.
export const SearchItem = z.object({
  package: z.object({
    name: z.string().min(1),
    version: z.string().min(1),
    date: z.string().regex(/^\d{4}-\d{2}-\d{2}T/),
  }),
})

export const SearchResponse = z.object({
  total: z.number().int().nonnegative(),
  objects: z.array(SearchItem),
})

export type SearchResponse = z.infer<typeof SearchResponse>

// The pitfall: the envelope is checked, the records inside it are not.
export const EnvelopeOnly = z.object({
  total: z.number().int().nonnegative(),
  objects: z.array(z.unknown()),
})

z.object strips keys you did not declare. Each recorded record also carries downloads, scores, maintainers, and links, which are dropped rather than checked, so a change to one of them cannot fail the parse.

Parse where the response enters the SDK

The method decodes the body, runs the check, and either returns the typed value or throws. A body that is not JSON gets the same error class with an empty path.

    async searchPackages(text: string, size = 20): Promise<SearchResponse> {
      const url = new URL('-/v1/search', base)
      url.searchParams.set('text', text)
      url.searchParams.set('size', String(size))
      const res = await get(url)
      if (res.status !== 200) throw new HttpError('searchPackages', res.status)
      let body: unknown
      try {
        body = JSON.parse(res.body)
      } catch {
        throw new ResponseShapeError('searchPackages', res.status, [{ path: '', message: 'body is not JSON' }])
      }
      const result = check(body)
      if (!result.ok) throw new ResponseShapeError('searchPackages', res.status, result.issues)
      return result.value
    },

The demo calls the method three times against a loopback stand-in: with the recorded body, with a field added to every record, and with one renamed field and one truncated record.

node --experimental-strip-types demo.ts
real     ok: 4 packages, first @actions/http-client 4.0.1, other keys: 0
added    ok: 4 packages, first @actions/http-client 4.0.1, other keys: 0
damaged  ResponseShapeError: searchPackages: response did not match the expected shape at objects.1.package.version, objects.3.package.version, objects.3.package.date

The added field passed and never reached the caller. The damaged body failed in searchPackages with all three paths, at the line that received it.

Compare the three validators on one body

src/checks.ts turns each library’s result into dotted paths. Ajv reports a missing property at its parent, so the adapter appends the property name from params.missingProperty.

node --experimental-strip-types compare.ts
zod                 objects.1.package.version, objects.3.package.version, objects.3.package.date
valibot             objects.1.package.version, objects.3.package.version, objects.3.package.date
ajv, allErrors      objects.1.package.version, objects.3.package.version, objects.3.package.date
ajv, defaults       objects.1.package.version
zod, envelope only  accepted

All three name the same three paths once Ajv has allErrors, which is off by default. The last line is the pitfall: a schema that checks total and that objects is an array accepts both damaged records.1

Check it worked

The tests hold the three validators to the same paths on the damaged body and on four neighbors of it, run the SDK against the stand-in, and type-check the sample with tsc.

node --experimental-strip-types --test test/sdk.test.ts | grep -E '^(ok|not ok)'
ok 1 - all three validators name the same failing paths
ok 2 - all three accept the recorded response and an added field
ok 3 - all three refuse the neighbors of the damaged body
ok 4 - an envelope-only schema lets the damaged records through
ok 5 - AJV stops at the first error unless allErrors is set
ok 6 - the SDK returns typed data and strips fields it does not read
ok 7 - the SDK throws ResponseShapeError naming the paths
ok 8 - a non-JSON body and a 404 fail at the call site too
ok 9 - the sample type-checks
ok 10 - Zod and Valibot strip unread fields; AJV returns the body untouched
ok 11 - AJV removeAdditional "all" drops the unread fields
ok 12 - a proxy set in the environment never sees the loopback calls
ok 13 - the SDK speaks HTTPS to an https base URL and refuses other schemes

Test 4 is the envelope-only schema accepting the damaged body, with the full schema refusing it as the control. Test 10 pins the difference in output: Zod and Valibot return only declared keys, while Ajv hands back the body it validated, unless test 11’s option is set. Test 12 runs the demo with NODE_USE_ENV_PROXY=1 and a proxy on a closed port, which the SDK’s own http.Agent keeps out of the loopback calls.

Count the bundle bytes

Validation runs on every call, so its cost is per call and per download. A timing from a shared machine is not evidence, so the sample counts bytes instead. bundle.ts bundles the same check with esbuild for a browser, minified, and gzips it.

node --experimental-strip-types bundle.ts
bundle                      minified   gzip  modules
zod                            90028  26286       21
zod, import { z }             454110  93024       96
zod/mini                       17909   6148       13
valibot                         4723   1660        2
ajv, compiled at run time     135179  40766       89
ajv, standalone code            5394   1260        2

Valibot is the smallest of the libraries that check against a schema object at run time. Ajv’s standalone code gzips smaller still, because the compiler runs at build time and only the generated function ships. The import { z } line bundles 96 modules where import * as z bundles 21, and comes out five times larger minified.2

When it goes wrong

The check passes, but the page still shows undefined. The schema covered the envelope and declared the records inside it as z.unknown(). Declare every record as strictly as the envelope, as SearchResponse does.

Ajv names one path when three are wrong. Its default is to stop at the first error, so pass allErrors: true to the constructor whenever the error is for a person to read.

Fields the API sent but the schema does not declare reach callers with Ajv. Its validator returns true and leaves the data as it was. Return the parsed value from Zod or Valibot, or construct Ajv with removeAdditional: "all", which test 11 shows dropping them.

When not to do this

Do not validate inside a hot loop that already trusts the payload, such as a second read of a response the SDK checked once. Parse at the boundary and pass the typed value inward.

Do not declare every field of the response to be thorough. A schema of the whole payload fails on a field your code never reads, and each such failure is an alarm about nothing.

Do not ship Zod’s full build to a browser bundle for one schema. zod/mini or Valibot do the same job here in a fifth of the minified bytes or less.

Last verified

Verified 2026-11-30 against Node 22.23.5, Zod 4.6.7, Valibot 1.5.0, Ajv 8.20.0, esbuild 0.28.2 and TypeScript 5.9.3. Every output block is what the command preceding it printed. All three validators ran. No timing was measured; the bundle sizes are byte counts from esbuild.

Footnotes

  1. The npm registry’s search response puts the records in a field called objects and the count in total, and returns at most 250 records per page, according to the registry API document. The recorded body reports a total of 817,217 matches for “http client”, of which it carries four. ↩︎ Back to text

  2. Zod’s own documentation writes the import as import * as z from "zod". It leaves the bundle question to Zod Mini, which it describes as a tree-shakable variant of Zod with the same features behind a functional API. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.