Skip to main content

[003] Zod as a request parser

  • Status: accepted
  • Author: @antonve
  • Date: 2022-12-20

Context

We were never parsing API responses. Up til now we defined a TypeScript type and assigned that type to the response of the fetch request. This works but has its limitations. It assumes that the backend is always right, and will return this type. This ignores the possibility of human error

Considered options

Zod

A parser for JavaScript objects. You define a schema, then try to parse the object against the schema, and fail early in case an unexpected result is returned. It's also able to generate TypeScript types based on the schema. The developer experience is really smooth, which is the main reason for picking it. It's also supported by other libraries we use (such as react-hook-form).

Others

I've seen benchmarks showing that Zod isn't the most performing object parser out there. However, since we're only using it on the client side and it's not in the critical path of the render phase.

Decision

Use Zod. It's good.

Outcome

It's been great to finally have confirmation that the API is returning correct data.