TypeScript types describe what your code expects, but they do not verify data arriving from an HTTP request, form submission, environment variable, database, or third-party API. This guide compares Zod, Valibot, and Standard Schema-compatible approaches, then shows reusable patterns for parsing unknown JSON, formatting validation errors, and choosing a runtime validation strategy that fits your application.
Overview
Whenever data crosses a trust boundary, TypeScript starts with an important limitation: types disappear at runtime. An interface such as interface User { id: string } does not check whether a received object actually contains a string id. A type assertion can silence the compiler, but it cannot make malformed input safe.
Runtime validation closes that gap by applying a schema to an unknown value. A schema describes the expected shape and rules; a parser checks the value and returns either validated data or structured issues. This gives an application a clear boundary between untrusted input and trusted internal data.
const input: unknown = await response.json();
const result = UserSchema.safeParse(input);
if (!result.success) {
// Reject, log, or map the validation issues.
throw new Error('Invalid user response');
}
const user = result.data; // validated and inferred by TypeScript
Zod and Valibot are validation libraries with their own schema APIs. Standard Schema is different: it is an interoperability contract that compatible libraries can implement. It can help application or framework code accept schemas from more than one library without depending on every library's proprietary API.
How to compare options
Do not choose a validator only by looking at its TypeScript inference. Compare the boundary you need to protect, the shape of your errors, the amount of transformation your application requires, and the environments where the schema will run.
- Input coverage: List the sources that are genuinely untrusted, such as JSON responses, request bodies, query strings, cookies, uploaded data, and environment variables.
- Failure behavior: Decide whether an invalid value should produce a 400 response, a field-level form error, a startup failure, a retry, or an internal alert.
- Schema ownership: Establish whether schemas live beside routes, in a shared package, or next to generated API types. A schema should have an identifiable owner when the contract changes.
- Runtime constraints: Consider browser bundle budgets, serverless cold starts, edge runtimes, and whether the same schema runs on both server and client.
- Async requirements: Separate structural checks from asynchronous checks such as database lookups. Validation libraries differ in how they model and execute asynchronous parsing.
- Interoperability: If a framework, form library, or internal platform supports Standard Schema, that may reduce coupling to one validator's schema representation.
Also distinguish validation from business rules. A schema can check that an email is shaped like an email and that an amount is positive. Whether the account is allowed to spend that amount is usually a service or domain decision, not merely a parsing concern.
Feature-by-feature breakdown
| Concern | Zod | Valibot | Standard Schema-compatible approach |
|---|---|---|---|
| What it is | A schema and validation library with a fluent, readable API. | A modular schema and validation library designed around composable functions. | An interoperability contract; the actual behavior comes from a compatible validation library. |
| Bundle size | Measure the version and imports used by your build; the full dependency surface may be more than a narrowly composed alternative. | Often attractive when small, modular client bundles are a priority, but verify the resulting bundle rather than relying on general comparisons. | Not a bundle-size solution by itself. The selected implementation determines the shipped code. |
| Inferred types | Schema definitions can infer input and output types, including many common transformations. | Schema definitions can infer types through its composable pipeline. | Type inference depends on the implementing library and its TypeScript integration. |
| Error formatting | Provides structured issues that can be converted into field maps or API error payloads. | Provides structured issues with a compositional API for collecting and mapping failures. | Standardizes compatibility more than presentation. Your application still needs an error-mapping policy. |
| Transforms | Supports preprocessing, coercion, and output transformations; keep input and output types conceptually separate. | Supports pipelines and transformations; compose them deliberately so normalization is visible. | Transformation behavior is library-specific and should be tested at the integration boundary. |
| Async validation | Use the library's asynchronous parsing path when a schema includes asynchronous checks. | Use the corresponding asynchronous parsing support where the chosen schema operations require it. | Compatibility does not remove the need to handle promises, failure modes, and request lifecycles correctly. |
| Framework support | Commonly integrated directly through adapters or custom route and form helpers. | Can be integrated directly or through ecosystem adapters where available. | Useful when a framework or form layer accepts any Standard Schema-compatible validator. |
A reusable schema pattern
The exact imports vary by library version and module system, but the boundary pattern is stable. Keep the schema close to the external contract, parse unknown, and export inferred types for internal consumers.
const UserSchema = z.object({
id: z.string().min(1),
email: z.string().email(),
displayName: z.string().min(1).max(80),
roles: z.array(z.enum(['admin', 'member']))
});
type User = z.infer<typeof UserSchema>;
export function parseUser(value: unknown): User {
return UserSchema.parse(value);
}
Use a throwing parser when invalid data should stop the current operation and a result-based parser when the caller needs to choose the response. For an API endpoint, a result-based function often makes the HTTP behavior explicit:
const parsed = UserSchema.safeParse(request.body);
if (!parsed.success) {
return response.status(400).json({
error: 'VALIDATION_ERROR',
fields: toFieldErrors(parsed.error)
});
}
return response.json(parsed.data);
Map issues without leaking implementation details
Clients generally need stable field names and messages, not the complete internal error object. Build one mapper for each public error format and test it with nested objects, arrays, missing fields, and invalid types.
type FieldErrors = Record<string, string[]>;
function addError(map: FieldErrors, path: readonly (string | number)[], message: string) {
const key = path.length ? path.join('.') : '_form';
(map[key] ??= []).push(message);
}
function toFieldErrors(error: { issues: Array<{ path: (string | number)[]; message: string }> }): FieldErrors {
const result: FieldErrors = {};
for (const issue of error.issues) {
addError(result, issue.path, issue.message);
}
return result;
}
Keep messages appropriate to the audience. A public response should not expose database details, secrets, stack traces, or internal schema names. Log enough context for diagnosis while treating the original payload as potentially sensitive.
Best fit by scenario
Choose Zod when readability and ecosystem familiarity matter
Zod is a practical choice for teams that want a widely recognizable schema style, direct inferred types, and a straightforward parse or safe-parse workflow. It fits route validation, shared domain objects, configuration checks, and form schemas. Keep schemas focused: a request-body schema should not automatically become a database model or a public response schema.
Choose Valibot when composition and client footprint are priorities
Valibot is worth evaluating when you want a modular functional style or need to pay close attention to client bundle composition. Confirm the result in your own build, especially when schemas are shared between server-rendered code and browser code. Its smaller individual operations do not remove the need to inspect the complete dependency graph.
Use Standard Schema compatibility when you want a replaceable boundary
Standard Schema is a good fit for reusable packages, framework integrations, and teams that want application code to depend on a common schema capability rather than a single validator's proprietary types. It does not replace the need to choose a concrete implementation, define error presentation, or document transformation behavior.
Combine generated types with runtime schemas carefully
OpenAPI or other contract tooling can generate useful TypeScript types, but generated types alone do not validate runtime data. For a stronger boundary, use the API contract to generate or inform schemas, then keep validation tests alongside the endpoint. See the guide to generating TypeScript types from OpenAPI and the comparison of TypeScript API client generation workflows.
The same principle applies to configuration. Validate environment input once during startup and expose a typed configuration object to the rest of the application. The type-safe environment variables guide covers the surrounding Node, Vite, Next.js, and Docker patterns.
When to revisit
Runtime validation should be reviewed whenever the data contract changes, not only when a dependency releases a new version. Schedule a focused check when you add an endpoint, change a form, introduce a third-party integration, move code between server and browser, or replace one validation library with another.
- Recheck the boundary: Confirm every external value still enters as
unknownor an equivalent untrusted representation before parsing. - Compare library changes: Review the current APIs, TypeScript compatibility, Standard Schema support, async behavior, adapters, and release notes before upgrading.
- Measure the build: Recheck browser and server bundles after changing imports or sharing schemas across packages.
- Test failure contracts: Verify status codes, field names, messages, nested paths, and redaction rules. Error formatting is part of your API behavior.
- Retest transformations: Confirm whether parsed output is normalized, coerced, or merely checked. Update callers when input and output types diverge.
- Keep a migration seam: Wrap parsing and error mapping behind small functions. This makes a future move from Zod to Valibot, or to another Standard Schema-compatible library, a controlled change rather than a repository-wide rewrite.
A useful baseline is simple: validate at every trust boundary, infer types from the schema where practical, expose stable errors to callers, and test the rejected cases as carefully as the successful ones. That approach remains valuable even as validators, adapters, and framework integrations change.