Skip to main content

Lesson 2 of 8

Full-Stack Type Safety - API Contract

With shared types from the `@task-manager/shared` package, every `fetch()` call on the client and every route handler on the server can reference the same type. A breaking API change immediately surfaces as a compile error on both sides - this is end-to-end type safety without tRPC.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Typed API Contract - Shared Between Client & Server

Typed API Contract - Shared Between Client & Server
// packages/shared/src/api.ts - API contract definitions ─────
import type { Task, CreateTaskDTO, TaskStatus } from "./types";

// REST API response shapes - shared contract:
export interface ApiResponse<T> {
  ok:   true;
  data: T;
}
export interface ApiError {
  ok:      false;
  code:    string;
  message: string;
  fields?: Record<string, string[]>;
}
export type ApiResult<T> = ApiResponse<T> | ApiError;

// Paginated response:
export interface Paginated<T> {
  items:   T[];
  total:   number;
  page:    number;
  perPage: number;
}

// API endpoint types - the contract both sides must honour:
export interface TaskApi {
  "GET    /tasks":         (q?: { status?: TaskStatus; page?: number }) => Promise<Paginated<Task>>;
  "GET    /tasks/:id":     (id: number) => Promise<Task>;
  "POST   /tasks":         (body: CreateTaskDTO) => Promise<Task>;
  "PATCH  /tasks/:id":     (id: number, body: Partial<CreateTaskDTO>) => Promise<Task>;
  "DELETE /tasks/:id":     (id: number) => Promise<void>;
}

// ── Server - implements the contract ─────────────────────────
// packages/server/src/routes/tasks.ts
import type { Task, CreateTaskDTO, Paginated } from "@task-manager/shared";
import { CreateTaskSchema }                    from "@task-manager/shared";

router.get("/tasks", async (req, res, next) => {
  try {
    const tasks: Paginated<Task> = await taskService.findPaginated({
      status: req.query.status as TaskStatus,
      page:   Number(req.query.page) || 1,
    });
    res.json({ ok: true, data: tasks });
  } catch (err) { next(err); }
});

router.post("/tasks", async (req, res, next) => {
  const parsed = CreateTaskSchema.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ ok: false, code: "VALIDATION_ERROR", ...parsed.error.flatten() });
    return;
  }
  try {
    const task: Task = await taskService.create(parsed.data, req.user!.id);
    res.status(201).json({ ok: true, data: task });
  } catch (err) { next(err); }
});

// ── Client - consumes the contract ───────────────────────────
// packages/client/src/api/tasks.ts
import type { Task, CreateTaskDTO, Paginated, ApiResult } from "@task-manager/shared";
import { CreateTaskSchema }                               from "@task-manager/shared";

const API_BASE = import.meta.env.VITE_API_URL ?? "http://localhost:3000/api/v1";

// Both client and server import from the same shared package -
// change Task in shared → BOTH get a compile error immediately.

async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(`${API_BASE}${path}`, {
    ...init,
    headers: { "Content-Type": "application/json", ...init?.headers },
  });
  const body: ApiResult<T> = await res.json();
  if (!body.ok) throw new Error(body.message);
  return body.data;
}

export const taskApi = {
  getAll: (params?: { status?: string }) =>
    apiFetch<Paginated<Task>>(`/tasks?${new URLSearchParams(params as Record<string, string>)}`),

  getById: (id: number) => apiFetch<Task>(`/tasks/${id}`),

  create: (input: CreateTaskDTO) =>
    apiFetch<Task>("/tasks", { method: "POST", body: JSON.stringify(input) }),
};

Common Mistakes

  • Duplicating types in client and server instead of sharing - two copies of `Task` will drift over time. The single shared package is the enforcer.
  • Not versioning the API contract - when the shared type changes in a breaking way, bump a version (or use `@ts-expect-error` migration markers) so consumers know to adapt.
  • Forgetting `import.meta.env` typing for Vite - Vite exposes env vars via `import.meta.env`. Add a `vite-env.d.ts` with `interface ImportMetaEnv { readonly VITE_API_URL: string }` to type them.

Tip

Tip

Practice FullStack Type Safety API Contract in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Full-Stack Type Safety - API Contract

Practice Task

Note

Practice Task - (1) Write a working example of FullStack Type Safety API Contract from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with FullStack Type Safety API Contract is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Key Takeaways

  • With shared types from the `@task-manager/shared` package, every `fetch()` call on the client and every route handler on the server can reference the same type.
  • Duplicating types in client and server instead of sharing - two copies of `Task` will drift over time. The single shared package is the enforcer.
  • Not versioning the API contract - when the shared type changes in a breaking way, bump a version (or use `@ts-expect-error` migration markers) so consumers know to adapt.
  • Forgetting `import.meta.env` typing for Vite - Vite exposes env vars via `import.meta.env`. Add a `vite-env.d.ts` with `interface ImportMetaEnv { readonly VITE_API_URL: string }` to type them.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done