Shared types and code between client and server

Intermediate · 23 min

Share Zod schemas and inferred types between Taskboard's client and API, and see where a shared type lies, such as dates that cross the wire as strings.

Before thisMonorepo layout for full-stack projects

Seattle JS · 23 min

Shared types and code between client and server

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Seattle JSReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A TypeScript type disappears at runtime, so sharing a type alone does not stop a bad request; a shared schema does both jobs.
  • With Zod, one schema gives you a runtime check and, through z.infer, the static type, so the two cannot disagree.
  • z.input is what callers may send and z.output is what the code receives after defaults and transforms, and they differ.
  • JSON has no Date type, so a Date sent over the wire arrives as a string, and a shared type that says Date is wrong on the client.
  • Share what both sides must agree on, and keep database row types and server-only logic out of the shared package.

Why a type alone is not enough

The previous lesson gave Taskboard a packages/shared folder. The tempting first thing to put in it is a type:

export type CreateTaskInput = { projectId: number; title: string; status?: "todo" | "doing" | "done" };

Both sides import it. The client builds a body that matches it. The API declares that the body it reads matches it. The compiler is happy.

But the compiler only runs on your code. A request from curl, a stale browser tab, or a script someone wrote last week never went through your compiler. At runtime TypeScript types are gone, so the handler gets whatever arrived. The type said “trust me” and nothing checked.

The fix is to share something that exists at runtime: a schema.

One schema, two jobs

Here is the shared package I used for Taskboard, with Zod 4.6.7:

import { z } from "zod";

export const TaskStatus = z.enum(["todo", "doing", "done"]);

export const CreateTaskInput = z.object({
  projectId: z.number().int().positive(),
  title: z.string().trim().min(1, "Give the task a title").max(120),
  status: TaskStatus.default("todo"),
});

export type CreateTaskInput = z.input<typeof CreateTaskInput>;
export type NewTask = z.output<typeof CreateTaskInput>;

The schema checks data at runtime. The same schema describes the data to the compiler through inference. Because both come from one definition, they can’t disagree. The API calls CreateTaskInput.safeParse(body). The client calls it too, before sending, so the form can show “Give the task a title” without a round trip. The TypeScript roadmap covers validating untrusted data at runtime; the next group’s lesson on validating on the client and the server builds on this.

I ran the API in-process against this schema:

201 { id: 1, projectId: 1, title: 'Write docs', status: 'todo' }
422 { errors: [ { path: 'title', message: 'Give the task a title' } ] }

Notice that " Write docs " came back as 'Write docs' (the trim() ran) and that status appeared although the caller never sent it (the default ran).

Input and output are different types

That second observation is why the code above exports two types. A schema with defaults and transforms has a before and an after:

  • z.input<typeof CreateTaskInput>: what a caller may send. status is optional.
  • z.output<typeof CreateTaskInput>: what the handler receives. status is always there.

The client’s createTask(input: CreateTaskInput) takes the input type, so it may leave status out. The handler works with NewTask, where it is guaranteed. Using one type for both would force you to pretend the field is both optional and required.

Where a shared type lies: the wire

Shared types are most dangerous when they look most helpful. Take a response type:

type Task = { id: number; createdAt: Date };

Both sides import it. The server builds a Task with a real Date. The server sends it as JSON. JSON has no date type, so createdAt goes over the wire as a string. On the client, a cast (or an unchecked res.json()) says it is a Date. I ran exactly that:

string 2026-11-22T10:00:00.000Z
TypeError: wire.createdAt.getFullYear is not a function

It type-checked. It crashed at runtime. The type described the data before it crossed the boundary, and the client read it after. The same trap applies to Map, Set, BigInt and undefined, which JSON drops or rejects.

There are two honest fixes. Describe the wire format in the type (createdAt: string), or parse the response with a schema that converts it:

const TaskWire = z.object({
  id: z.number(),
  createdAt: z.iso.datetime().transform((s) => new Date(s)),
});

I ran this too: TaskWire.parse(wire) produced a real Date, and z.input came out as the string form while z.output was the Date. This is the same input/output split, doing real work. The rule: a shared type should describe what crosses the wire, not what your server held in memory.

What belongs in shared

Belongs Why
Request-body schemas Both sides validate against the same rules
Response shapes, in wire form The client’s idea of the response matches the server’s
Enums and constants (statuses, limits) One list, no drift
Pure helpers (formatting a title) No environment assumptions
Does not belong Why
Database row types They are your table layout, not your public contract, and they can include columns you must never send, such as password_hash
Anything importing a database driver It would ship to the browser
Anything reading process.env or window It only works on one side
Authorization logic The client may hide a button, but only the server may decide

The row types point deserves a second look. It is tempting to export the Drizzle table type and use it as the response type everywhere, because it saves writing a second type. Do not. Your API’s shape is a promise to clients; your table layout is an implementation detail. If you tie them together, renaming a column becomes a breaking change for every client, and adding a sensitive column leaks it by default. Write the response type separately, and map to it. End-to-end type safety shows a way to make that mapping cheap.

A habit that pays off

When you add a field, change the schema first. The compiler then lights up every place that needs updating, on both sides, in one run. If a change doesn’t start in shared, ask why. That is usually a sign that the two sides are about to disagree.

What the video covers

Seattle JS’s “Sharing TypeScript Types Across the Stack” is a 23-minute talk by Evan Tahler, published in March 2021. Its description says that once you are deep into TypeScript you start to see the benefit of using complex types across all parts of an application, and that it covers the controller side of this. It is a talk from 2021, before Zod-style schema inference became the default way to do this, so treat the specific tools as dated. The question it asks, how types travel across layers, is the same one. I could not read a transcript to check how it treats the runtime-check problem this lesson focuses on.

Where this fits

You have a shared contract for data in motion. The data at rest needs a home with a reproducible setup, so the next lesson runs Postgres and storage on your machine: a local environment with Docker Compose.

Check yourself

  1. 01Why is sharing a plain TypeScript interface not enough to protect the API?

    Types are erased when the code runs, so a request with the wrong shape still reaches the handler. A schema checks the real data at runtime.

  2. 02What is the difference between z.input and z.output for a schema with a default?

    z.input is the shape a caller may send, where the defaulted field is optional. z.output is the shape the handler gets, where the default has been filled in.

  3. 03A shared type says createdAt is a Date. What does the client actually receive?

    A string, because JSON cannot carry a Date. Calling a Date method on it fails at runtime even though the code type-checks.

  4. 04Why not reuse the database row type as the API response type?

    It couples your public contract to your table layout and can leak columns such as password hashes. A separate response type lets each change independently.

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark