Shared Type Definitions in Monorepos
What you'll learn: How to create a dedicated types package that both your backend and frontend import, ensuring perfect API contract alignment.
The Problem: Duplicated or Diverging Types
When you build a full-stack TypeScript application with separate frontend and backend projects, you face a dilemma. Your API endpoint returns a User object—should you define that type in the backend, the frontend, or both?
Duplicating the type in both places creates maintenance burden and drift. Defining it only in one place means the other side has no type safety. The solution: a shared types package that both projects import.
What Are Shared Type Packages?
In a monorepo (a single repository containing multiple related packages), you can create a dedicated package—often called @yourapp/types or shared-types—that exports all your API contracts: request bodies, response shapes, database models, and domain types.
Both your backend and frontend import from this single source. When the API contract changes, you update one definition, and TypeScript immediately flags mismatches in both consuming projects.
The Mental Model
Think of the shared types package as a contract document that both parties sign. The backend promises to return data matching these types. The frontend promises to handle data of these shapes. Neither can drift without the compiler catching it.
This becomes especially powerful in monorepos managed by tools like pnpm workspaces, Turborepo, or Nx, where all packages share the same node_modules and type-checking can run across the entire codebase.
Why This Matters for End-to-End Type Safety
You've learned how to validate runtime data with Zod and infer types from schemas. You've seen how to type fetch responses. Shared types bring these together: your backend defines the schema, exports the inferred type from the shared package, and your frontend imports that exact type for its API calls—all synchronized automatically.
Key Takeaway: A shared types package eliminates API contract duplication and drift by providing a single source of truth that both backend and frontend import, giving you compile-time guarantees across your entire stack.