Skip to content

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.

18 min read0/5 questions

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.

Predict the outputTypeScript

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));
Need a nudge? Hints walk you through it.

There are three ways to close the gap, and real companies mix them:

  1. Validate at runtime: describe the expected shape as a schema and check every response or request against it.
  2. Generate types from a contract: the backend publishes a machine-readable description (OpenAPI), and the frontend generates its types from it.
  3. Share code: frontend and backend are both TypeScript, and the client imports the server's types directly (tRPC, Server Actions).
Three ways to keep both sides in agreement
Backend: FastAPI / NodeBackendFastAPI / NodeRuntime schema: Zod parseRuntime schemaZod parseopenapi.json: contractopenapi.jsoncontractShared TS types: typeof routerShared TS typestypeof routerFrontend: typed callsFrontendtyped callsJSONchecked datapublishescodegenexports typeimport type

Runtime validation checks the real bytes on every request. It catches anything, including a server that drifted, at a small CPU cost.

1/3

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:

src/lib/schemas/signup.ts
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 checked

For 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:

src/lib/parse.ts
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.ts

openapi-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:

src/api/client.ts
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 it in order5 steps

Put the steps of a codegen workflow that catches contract drift in CI in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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:

server/router.ts
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;
client/trpc.ts
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:

app/settings/actions.ts
"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 the pairs0/5 matched

Match each situation to the approach that fits best.

Choose an item, then its match on the other side.

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:

  1. Expand: the server returns both fields. Nothing breaks, because old clients read created_at and ignore the new one.
  2. Migrate: ship clients that read createdAt. Wait until traffic from old clients is gone, which you confirm with logs or metrics, not by guessing.
  3. 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:

ChangeSafe for old clients?Safe for old servers?
Server adds a response fieldYes, if clients do not use strict schemasn/a
Server removes or renames a response fieldNo: expand and contractn/a
Server adds an optional request fieldYesn/a
Server adds a required request fieldNo: old clients do not send itn/a
Client starts sending a new fieldn/aOnly 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:

TypeScript
type Rule<T> = (raw: string | undefined) => T; const url: Rule<string> = (raw) => { if (!raw) throw new Error("is missing"); try { return new URL(raw).toString(); } catch { throw new Error("is not a URL"); }}; const port: Rule<number> = (raw) => { const n = Number(raw ?? "3000"); if (!Number.isInteger(n) || n < 1 || n > 65535) throw new Error("must be a port number"); return n;}; const oneOf = <const T extends string>(...allowed: T[]): Rule<T> => (raw) => { if (!allowed.includes(raw as T)) throw new Error(`must be one of ${allowed.join(", ")}`); return raw as T;}; function loadEnv<S extends Record<string, Rule<unknown>>>( rules: S, source: Record<string, string | undefined>,): { [K in keyof S]: ReturnType<S[K]> } { const out: Record<string, unknown> = {}; const problems: string[] = []; for (const [key, rule] of Object.entries(rules)) { try { out[key] = rule(source[key]); } catch (e) { problems.push(`${key} ${(e as Error).message}`); } } if (problems.length > 0) throw new Error(`Invalid environment:\n ${problems.join("\n ")}`); return out as { [K in keyof S]: ReturnType<S[K]> };} const rules = { DATABASE_URL: url, PORT: port, NODE_ENV: oneOf("development", "production", "test") }; const env = loadEnv(rules, { DATABASE_URL: "postgres://db:5432/app", NODE_ENV: "production" });console.log(env.PORT + 1, env.NODE_ENV); try { loadEnv(rules, { DATABASE_URL: "", PORT: "99999", NODE_ENV: "prod" });} catch (e) { console.log((e as Error).message);}
Output
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.

src/env.ts
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.

Quick check
A form library is typed with z.output<typeof SignupSchema> for its field values, where age is z.coerce.number(). What goes wrong?
Need a nudge? A hint rules out a wrong answer.
Quick check
A Server Action is declared async function deletePost(id: string) and only ever called from your own typed component. Why validate id inside it?
Need a nudge? A hint rules out a wrong answer.

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.

Key terms
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.