Skip to content
Backend & APIChapter 26 / 57Advanced6 min read

Shared API Contracts

Share a typed API contract between frontend and backend. Keep request and response in one module so a field rename fails the build on both sides.

On this page

1. What is this practice?

A contract is a promise: "send this to this endpoint, and you get this back". When the promise is written in two separate places, the two will drift apart sooner or later. When it is written in one place, TypeScript keeps both in step.

2. Why does it matter?

A backend developer renamed fullName to name. The frontend's own type still says fullName. The build is green, it gets deployed, and every user's name shows as undefined on the profile page. Someone noticed three days later.

The other bug goes the opposite way. A route returned the whole database row. The row also had password_hash and reset_token. The frontend does not use them, but anyone can see them in the network tab.

Two separate type copiesOne shared contract
A field rename breaks at runtimeA field rename fails the build
Backend and frontend each write their own typeBoth import one module
The route sends the whole rowThe route builds only the fields in the contract
A new developer does not know what an endpoint acceptsThe contract file is itself the documentation
A breaking change quietly breaks the public APIA public API changes behind a version prefix

3. When to follow it

LevelHow importantWhy
Learning projectOptionalWhen frontend and backend are in one file the benefit is small
Production codeImportantDifferent people change the frontend and backend, so drift is certain
Senior levelDecide where the contract lives and how it is versionedA public API, a mobile app and the web all run on one promise

When to learn it: after Input Validation and Types Beside Logic, when your frontend and API both start growing in one repo.

4. Bad vs good code

Bad: its own type on each side

ts
type Project = {
  id: string;
  title: string;
  ownerName: string;
};

export async function GET() {
  const rows = await listProjectsWithOwners();
  return Response.json(rows);
}
ts
type Project = {
  id: string;
  name: string;
  ownerName: string;
};

const projects: Project[] = await fetch("/api/projects").then((res) => res.json());

The route's type says title, the frontend says name, and the actual response is whatever was in the row. The compiler says nothing.

Good: one contract module

File lib/api/contracts/projects.contract.ts:

ts
import { z } from "zod";

export const projectSchema = z.object({
  id: z.uuid(),
  name: z.string(),
  ownerName: z.string(),
  createdAt: z.iso.datetime(),
});

export const createProjectRequestSchema = z.object({
  name: z.string().trim().min(1).max(120),
});

export type Project = z.infer<typeof projectSchema>;
export type CreateProjectRequest = z.infer<typeof createProjectRequestSchema>;
export type ListProjectsResponse = { projects: Project[] };

The service turns a row into the contract, field by field:

ts
export function toProject(row: ProjectWithOwnerRow): Project {
  return {
    id: row.id,
    name: row.name,
    ownerName: row.owner_name,
    createdAt: row.created_at,
  };
}

The route returns that same type:

ts
export async function GET() {
  const user = await requireUser();
  const rows = await listProjectsForUser(user.id);

  return NextResponse.json<ListProjectsResponse>({ projects: rows.map(toProject) });
}

The frontend client imports the same thing:

ts
import type { CreateProjectRequest, ListProjectsResponse, Project } from "@/lib/api/contracts/projects.contract";

export function listProjects() {
  return apiRequest<ListProjectsResponse>("/api/projects");
}

export function createProject(input: CreateProjectRequest) {
  return apiRequest<{ project: Project }>("/api/projects", { method: "POST", body: input });
}

Now if you rename name to title, toProject, the route and every component that reads project.name will all give a compile error together.

What is the difference?

ThingBad codeGood code
Type copiesTwo, separateOne contract module
ResponseThe whole row, secrets includedtoProject, only the named fields
Renameundefined at runtimeAn error at compile time
Request shapeNot written anywhereA Zod schema, the server validates with it too

5. How to apply it

Contract first
Write the request and response schema for the endpoint
Let the route validate its input with this schema
Let the service map a row into the contract shape
Let the frontend client import these same types
When the contract changes, both sides are compile checked

For a public API, such as one used by partners or a mobile app, create a new version on a breaking change (/api/v2/...) and write the end date of the old version in the docs. Mobile apps keep running on old versions for months.

6. Exceptions and common mistakes

If the frontend and backend are in separate repos, publish the contract in a small shared package, or generate types from an OpenAPI spec. Tools like server actions and tRPC share types on their own, so there is less need for a separate contract file, but the rule "return only the named fields" still applies.

Mistake: Using a database row directly as the response

Why? The moment a new column is added it leaks into the API, whether it is a password hash or an internal note.

Better: Write a mapper function that picks only the contract's fields.

Mistake: Writing the response type yourself on the frontend

Why? That type never stays in sync with the backend and gives false safety.

Better: Import the type from the contract module, and never declare the shape on the frontend.

Mistake: Using a database type in the contract

Why? A column rename directly breaks the public API and snake_case names reach the client.

Better: Give the contract its own shape and let the mapper bridge the two.

Mistake: Quietly removing a field from a public API

Why? Old mobile apps and partner integrations break without warning.

Better: Make breaking changes under a new version prefix and add a deprecation note.

7. What to learn before and after

Final quick revision

CheckQuestion
One placeDo the request and response shapes live only in the contract module?
ImportDo both the route and the client import the same thing?
MapperWas the response built field by field, not by spreading a row?
ValidationIs the request schema also the server validation?
VersioningIs a breaking change to a public API in a new version?