Lesson 48 of 50TypeScript
End-to-End Type Safety
Keep types true across the network with Zod 4 schemas, Standard Schema, OpenAPI codegen, tRPC and Server Actions, and validate env vars at startup.
A backend developer renames created_at to createdAt in one endpoint. The frontend still compiles, every test passes, and the order page shows "Invalid Date" to every customer. Nothing was wrong with either codebase's types. The bug lived in the gap between them: the network. Type Safety in Practice showed how to validate data at the edge with Zod. This lesson zooms out to the whole system: how teams keep the frontend, backend and configuration in agreement, which of the three main approaches fits which situation, and the mistakes that let wrong data through even when everything is "typed".
The network erases types
TypeScript types exist only at compile time. A response body is a string of bytes that JSON.parse turns into whatever shape it happens to have. Any type you put on it is a claim, and a claim about code owned by another team, deployed on another schedule, is the weakest kind.
What does this print?
type Order = { id: string; createdAt: string };
const body = '{"id":"o1","created_at":"2026-10-01T09:00:00Z"}';
const order = JSON.parse(body) as Order;
const placed = new Date(order.createdAt);
console.log(order.id, placed.getFullYear(), String(placed));There are three ways to close the gap, and real companies mix them:
- Validate at runtime: describe the expected shape as a schema and check every response or request against it.
- Generate types from a contract: the backend publishes a machine-readable description (OpenAPI), and the frontend generates its types from it.
- Share code: frontend and backend are both TypeScript, and the client imports the server's types directly (tRPC, Server Actions).
Runtime validation checks the real bytes on every request. It catches anything, including a server that drifted, at a small CPU cost.
Zod 4 schemas as the source of truth
With runtime validation, the schema is the one definition, and the TypeScript type is derived from it. Zod 4 is the current version. Many tutorials still show Zod 3, so watch for two changes: string formats moved to the top level (z.email(), z.url(), z.uuid()), and custom messages use the error option instead of message.
The detail that trips people at work is that a schema has two types, not one:
import { z } from "zod";
export const SignupSchema = z.object({
email: z.email({ error: "Enter a valid email" }),
age: z.coerce.number().int().min(13, { error: "You must be 13 or older" }),
newsletter: z.stringbool().default(false),
tags: z.string().transform((s) => s.split(",").map((t) => t.trim()).filter(Boolean)),
});
export type SignupInput = z.input<typeof SignupSchema>;
// what you may pass in: age can be a string, newsletter is optional, tags is a string
export type Signup = z.output<typeof SignupSchema>;
// what you get out: { email: string; age: number; newsletter: boolean; tags: string[] }z.infer is the same as z.output. Use z.input for the type of raw form values or query strings, and z.output for the data your code works with after parsing. Mixing them up produces the classic bug of a form library typed with the output type, so TypeScript insists age is a number while the input element hands you a string.
Errors should go back to the user, not into a log. safeParse never throws, and z.flattenError reshapes the issues into one list per field, ready for a form:
const result = SignupSchema.safeParse(Object.fromEntries(formData));
if (!result.success) {
const { fieldErrors } = z.flattenError(result.error);
// { email: ["Enter a valid email"], age: ["You must be 13 or older"] }
return { ok: false as const, fieldErrors };
}
const signup = result.data; // Signup, fully typed and checkedFor logs, z.prettifyError(error) gives a readable multi-line summary, and z.treeifyError gives a nested structure for deeply nested inputs.
Standard Schema: write code once for any validator
Zod is not the only option. Valibot is far smaller for bundle-sensitive pages, and ArkType is very fast. The Standard Schema spec lets libraries accept any of them. Each compliant schema exposes a ~standard property with a validate function and type information, so tRPC, TanStack Form and many others accept a Zod, Valibot or ArkType schema interchangeably.
You can use the same interface in your own helpers:
import type { StandardSchemaV1 } from "@standard-schema/spec";
export async function parseWith<S extends StandardSchemaV1>(
schema: S,
data: unknown,
): Promise<StandardSchemaV1.InferOutput<S>> {
let result = schema["~standard"].validate(data);
if (result instanceof Promise) result = await result;
if (result.issues) {
throw new Error(`Invalid data: ${result.issues.map((i) => i.message).join("; ")}`);
}
return result.value;
}A shared fetchJson(url, schema) built on this works for every team, whatever validator they picked.
Codegen from OpenAPI
When the backend is not TypeScript, share a contract instead of code. FastAPI generates an OpenAPI document from your Pydantic models and serves it at /openapi.json. The frontend turns it into types:
npx openapi-typescript http://localhost:8000/openapi.json -o src/api/schema.d.tsopenapi-typescript produces a single paths type describing every route, parameter and response. The small openapi-fetch client uses it so a wrong URL, a missing path parameter or a misspelt field is a compile error:
import createClient from "openapi-fetch";
import type { paths } from "./schema";
const api = createClient<paths>({ baseUrl: import.meta.env.VITE_API_URL });
export async function getItem(id: number) {
const { data, error } = await api.GET("/items/{item_id}", {
params: { path: { item_id: id } },
});
if (error) throw new Error(error.detail); // the 404 body type from the spec
return data; // { id: number; name: string; price_cents: number }
}Notice there is no <Item> written anywhere. The response type flows from the Pydantic model, through the spec, into the call site.
Codegen only works if the generated file stays current. The pattern teams use:
Put the steps of a codegen workflow that catches contract drift in CI in order.
- Tap the steps below in the right order.
The limit of codegen is that it trusts the spec. If the server returns something its own spec does not describe, the client types are wrong and nothing notices at runtime. For data that matters (money, permissions), teams still add a runtime schema at the boundary, sometimes generated from the same spec. Some codegen tools may lag behind new TypeScript releases, so check their support before a compiler upgrade.
Shared code: tRPC and Server Actions
When both sides are TypeScript in one repository, you can skip the contract entirely and import the server's types.
tRPC turns server functions into typed procedures. The client imports only the type of the router, so no server code reaches the browser bundle:
import { initTRPC, TRPCError } from "@trpc/server";
import { z } from "zod";
const t = initTRPC.create();
export const appRouter = t.router({
orderById: t.procedure
.input(z.object({ id: z.string() }))
.query(async ({ input }) => {
if (input.id === "missing") throw new TRPCError({ code: "NOT_FOUND" });
return { id: input.id, totalCents: 4200, status: "paid" as const };
}),
});
export type AppRouter = typeof appRouter;import { createTRPCClient, httpBatchLink } from "@trpc/client";
import type { AppRouter } from "../server/router";
const trpc = createTRPCClient<AppRouter>({ links: [httpBatchLink({ url: "/api/trpc" })] });
const order = await trpc.orderById.query({ id: "ord_1" });
order.status; // "paid"Rename totalCents on the server and the client fails to compile in the same pull request. Note that the .input() schema still validates at runtime: the shared type tells the client what to send, and the schema makes sure the server gets it.
Server Actions in Next.js go further: you import the server function itself and call it from a component. The types flow automatically, which makes it easy to forget that the arguments still cross the network. Anyone can call an action endpoint with any body, so the TypeScript parameter type is a hope, not a guarantee:
"use server";
import { z } from "zod";
const UpdateName = z.object({ name: z.string().trim().min(1).max(80) });
export async function updateName(input: { name: string }) {
const parsed = UpdateName.safeParse(input); // never trust the parameter type
if (!parsed.success) {
return { ok: false as const, fieldErrors: z.flattenError(parsed.error).fieldErrors };
}
// check the session and permissions here, then write parsed.data.name
return { ok: true as const };
}The trade-off with shared code is coupling. It works only for TypeScript clients, so a mobile app or a partner integration needs a separate API. And it assumes client and server deploy together. A browser tab that loaded yesterday's JavaScript can call today's server with yesterday's shapes, so changes to procedure inputs still need to stay backward compatible for a while.
Match each situation to the approach that fits best.
Changing a contract without breaking clients
Every approach above catches a mismatch. None of them makes a breaking change safe, because old clients keep running after you deploy: a browser tab left open overnight, a mobile app that users have not updated, a partner's integration. Senior engineers design changes so that both versions work at once.
The rule is expand, then contract. To rename created_at to createdAt:
- Expand: the server returns both fields. Nothing breaks, because old clients read
created_atand ignore the new one. - Migrate: ship clients that read
createdAt. Wait until traffic from old clients is gone, which you confirm with logs or metrics, not by guessing. - Contract: remove
created_at. Mark it deprecated in the OpenAPI spec first so codegen users see it coming.
Your client-side schemas affect this too. In Zod 4, z.object strips unknown keys: extra fields pass validation and are dropped from the result. z.strictObject rejects them, and z.looseObject keeps them. For responses from a server you do not deploy together with, use the default or loose form. A strict schema turns every harmless field the backend adds into an outage in every deployed client. Save strict schemas for inputs your own server receives, where an unexpected key is a sign of a bug or an attack.
Think about the direction of each change:
| Change | Safe for old clients? | Safe for old servers? |
|---|---|---|
| Server adds a response field | Yes, if clients do not use strict schemas | n/a |
| Server removes or renames a response field | No: expand and contract | n/a |
| Server adds an optional request field | Yes | n/a |
| Server adds a required request field | No: old clients do not send it | n/a |
| Client starts sending a new field | n/a | Only if the server ignores unknown keys |
Codegen and shared types make these breaks visible at compile time, but only inside one repository. Across teams, the contract file is the conversation: review changes to openapi.json in pull requests like you review a database migration.
Validate environment variables at startup
Configuration is another boundary. process.env.STRIPE_SECRET_KEY is typed string | undefined, and Declaration Files and Module Augmentation showed how easy it is to declare it as string without checking. The safe pattern is to parse the environment once, at startup, and import a typed object everywhere else. If a variable is missing, the app refuses to boot with a clear message instead of failing on the first payment three hours later.
Here is the idea with no library, so you can see every step:
Press Run (⌘ Enter) to see what happens.Two details matter. The loader collects every problem before failing, so a broken deploy shows the whole list at once. And the mapped return type means env.PORT is a number, derived from the rules, with no separate interface to keep in sync.
In a real project you would use Zod for the rules, and often the t3-env package, which adds one important feature: it separates server variables from client ones and throws if server code's secrets are read in a browser bundle.
import { createEnv } from "@t3-oss/env-core";
import { z } from "zod";
export const env = createEnv({
server: {
DATABASE_URL: z.url(),
STRIPE_SECRET_KEY: z.string().startsWith("sk_"),
},
clientPrefix: "PUBLIC_",
client: {
PUBLIC_API_URL: z.url(),
},
runtimeEnv: process.env,
});Import env from this module everywhere and ban direct process.env reads with a lint rule, so the validated object is the only way in.
z.output<typeof SignupSchema> for its field values, where age is z.coerce.number(). What goes wrong?async function deletePost(id: string) and only ever called from your own typed component. Why validate id inside it?That closes the TypeScript lessons. Next, Project: A Typed Expense Tracker puts them to work in one small app, from a typed model to a tested API client.
- trust boundary
- Any point where data enters from outside the process: network responses, requests, forms, env vars. Types are not guaranteed there.
- z.input / z.output
- The type a Zod schema accepts before parsing and the type it produces after transforms, defaults and coercion.
- Standard Schema
- A shared interface (
~standard) implemented by Zod, Valibot, ArkType and others, so libraries can accept any validator. - OpenAPI
- A machine-readable description of an HTTP API's routes, parameters and responses. FastAPI generates one automatically.
- codegen
- Generating TypeScript types (or clients) from a contract such as an OpenAPI document, usually in CI.
- tRPC
- A library that exposes server procedures to a TypeScript client by sharing the router's type, with runtime input validation.
- fail fast
- Validating configuration at startup so a bad deploy refuses to boot with a clear error, rather than failing later.