Final project
Overview
Time to put everything together. You’ll build task-board-api: a small but complete JSON API for a task board, written entirely in TypeScript and run directly by Node. It validates every request, returns precise error messages, is covered by tests — and has no build step.
Along the way it uses almost every topic in the course: object types and unions, narrowing, generics and utility types, classes with private fields, modules, async code, runtime validation with Zod, tsconfig, Vitest and Node’s built-in modules.
What you’ll build
$ curl -X POST localhost:3000/tasks -d '{"title":"Write the final lesson","priority":"high","tags":["course"]}'
{"title":"Write the final lesson","priority":"high","tags":["course"],"id":"1","done":false,"createdAt":"2026-12-04T10:51:29.971Z","updatedAt":"2026-12-04T10:51:29.971Z"}
$ curl -X POST localhost:3000/tasks -d '{"title":"","priority":"urgent"}'
{"error":"Validation failed","issues":["title: Too small: expected string to have >=1 characters","priority: Invalid option: expected one of \"low\"|\"medium\"|\"high\""]}
$ curl -X PATCH localhost:3000/tasks/1 -d '{"done":true}'
$ curl "localhost:3000/tasks?done=false&priority=high"
$ curl -X DELETE localhost:3000/tasks/1| Route | Success | Errors |
|---|---|---|
GET /health |
200 { ok: true } |
|
GET /tasks?done=&priority= |
200 Task[] |
400 bad filter |
POST /tasks |
201 Task |
400 validation |
GET /tasks/:id |
200 Task |
404 |
PATCH /tasks/:id |
200 Task |
400, 404 |
DELETE /tasks/:id |
204 |
404 |
Project setup
task-board-api/
├── package.json
├── tsconfig.json
├── src/
│ ├── schema.ts ← Zod schemas and the types derived from them
│ ├── store.ts ← TaskStore: an in-memory repository class
│ ├── router.ts ← a pure function: request in, response out
│ └── server.ts ← node:http glue, the only file that does I/O
└── test/
└── router.test.tsmkdir task-board-api && cd task-board-api
npm init -y
npm install zod
npm install -D typescript @types/node vitestpackage.json:
{
"name": "task-board-api",
"private": true,
"type": "module",
"scripts": {
"start": "node src/server.ts",
"dev": "node --watch src/server.ts",
"check": "tsc",
"test": "vitest run"
},
"dependencies": {
"zod": "^4.6.7"
},
"devDependencies": {
"@types/node": "^26.6.11",
"typescript": "^7.0.2",
"vitest": "^5.1.2"
}
}tsconfig.json — the configuration used throughout this course, now including the tests:
{
"compilerOptions": {
"module": "nodenext",
"target": "esnext",
"types": ["node"],
"strict": true,
"noUncheckedIndexedAccess": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true
},
"include": ["src", "test"]
}Step 1: schemas and types — src/schema.ts
import { z } from "zod";
export const Priority = z.enum(["low", "medium", "high"]);
export type Priority = z.infer<typeof Priority>;
const Title = z.string().trim().min(1).max(200);
const Tags = z.array(z.string().trim().min(1)).max(10);
/** Body of POST /tasks */
export const NewTask = z.object({
title: Title,
priority: Priority.default("medium"),
tags: Tags.default([]),
});
export type NewTask = z.infer<typeof NewTask>;
/** Body of PATCH /tasks/:id — any subset of fields, but at least one */
export const TaskPatch = z
.object({ title: Title, priority: Priority, tags: Tags, done: z.boolean() })
.partial()
.refine((patch) => Object.keys(patch).length > 0, "Send at least one field to change");
export type TaskPatch = z.infer<typeof TaskPatch>;
/** Query string of GET /tasks, e.g. ?done=false&priority=high */
export const TaskQuery = z.object({
done: z.enum(["true", "false"]).transform((value) => value === "true").optional(),
priority: Priority.optional(),
});
export type TaskQuery = z.infer<typeof TaskQuery>;
export type Task = NewTask & {
id: string;
done: boolean;
createdAt: string;
updatedAt: string;
};- Every request body and query string has a Zod schema, and every type comes from
z.infer— so validation and types can never disagree (Validating external data). NewTaskfills in defaults (priority: "medium",tags: []) and trims the title.TaskPatchreuses the same field rules with.partial()(a schema-levelPartial, see Utility types) and arefinethat rejects empty patches.TaskQueryturns the strings"true"/"false"from the URL into a realboolean.Taskis an intersection (Intersection types): a validatedNewTaskplus the fields the server controls.
Step 2: the store — src/store.ts
import type { NewTask, Task, TaskPatch, TaskQuery } from "./schema.ts";
export class TaskStore {
readonly #tasks = new Map<string, Task>();
readonly #now: () => Date;
#nextId = 1;
/** `now` is injectable so tests can control timestamps. */
constructor(now: () => Date = () => new Date()) {
this.#now = now;
}
list(query: TaskQuery = {}): Task[] {
return [...this.#tasks.values()].filter(
(task) =>
(query.done === undefined || task.done === query.done) &&
(query.priority === undefined || task.priority === query.priority),
);
}
get(id: string): Task | undefined {
return this.#tasks.get(id);
}
create(input: NewTask): Task {
const timestamp = this.#now().toISOString();
const task: Task = { ...input, id: String(this.#nextId++), done: false, createdAt: timestamp, updatedAt: timestamp };
this.#tasks.set(task.id, task);
return task;
}
update(id: string, patch: TaskPatch): Task | undefined {
const existing = this.#tasks.get(id);
if (existing === undefined) return undefined;
const updated: Task = { ...existing, ...patch, updatedAt: this.#now().toISOString() };
this.#tasks.set(id, updated);
return updated;
}
delete(id: string): boolean {
return this.#tasks.delete(id);
}
}- Private
#fields keep the data unreachable from outside the class, even at run time (Access modifiers). - The clock is injected through the constructor, so tests get predictable timestamps.
getandupdatereturnTask | undefined— “not found” is part of the type, and the router has to handle it (null and undefined).- The class only uses erasable syntax: fields are declared and assigned explicitly, without parameter properties, so Node can run it directly.
Step 3: the router — src/router.ts
import { z } from "zod";
import { NewTask, TaskPatch, TaskQuery } from "./schema.ts";
import type { TaskStore } from "./store.ts";
export type ApiRequest = {
method: string;
path: string;
query: URLSearchParams;
body: unknown;
};
export type ApiResponse = {
status: number;
body?: unknown;
};
type ErrorBody = { error: string; issues?: string[] };
function error(status: number, message: string, issues?: string[]): ApiResponse {
const body: ErrorBody = issues ? { error: message, issues } : { error: message };
return { status, body };
}
function invalid(zodError: z.ZodError): ApiResponse {
const issues = zodError.issues.map((issue) => `${issue.path.join(".") || "body"}: ${issue.message}`);
return error(400, "Validation failed", issues);
}
export function createRouter(store: TaskStore): (request: ApiRequest) => ApiResponse {
return function handle({ method, path, query, body }: ApiRequest): ApiResponse {
const [, resource, id, ...extra] = path.split("/");
if (resource === "health" && id === undefined) {
return method === "GET" ? { status: 200, body: { ok: true } } : error(405, "Method not allowed");
}
if (resource !== "tasks" || extra.length > 0) {
return error(404, `No route for ${path}`);
}
// /tasks
if (id === undefined || id === "") {
if (method === "GET") {
const parsed = TaskQuery.safeParse(Object.fromEntries(query));
return parsed.success ? { status: 200, body: store.list(parsed.data) } : invalid(parsed.error);
}
if (method === "POST") {
const parsed = NewTask.safeParse(body);
return parsed.success ? { status: 201, body: store.create(parsed.data) } : invalid(parsed.error);
}
return error(405, "Method not allowed");
}
// /tasks/:id
switch (method) {
case "GET": {
const task = store.get(id);
return task ? { status: 200, body: task } : error(404, `Task ${id} not found`);
}
case "PATCH": {
const parsed = TaskPatch.safeParse(body);
if (!parsed.success) return invalid(parsed.error);
const task = store.update(id, parsed.data);
return task ? { status: 200, body: task } : error(404, `Task ${id} not found`);
}
case "DELETE":
return store.delete(id) ? { status: 204 } : error(404, `Task ${id} not found`);
default:
return error(405, "Method not allowed");
}
};
}The router is the heart of the design: a pure function from an ApiRequest to an ApiResponse. It knows nothing about sockets, streams or headers, which makes every route testable with a plain function call.
- The request body arrives as
unknownand becomes typed data only aftersafeParsesucceeds. safeParseresults are discriminated unions: onsuccess,parsed.datais fully typed; otherwise the Zod issues become a readableissueslist.- Destructuring the path with
noUncheckedIndexedAccessmakesidastring | undefined, so the “no id” case can’t be forgotten. createRoutertakes the store as a parameter — dependency injection again, which is how the tests give it a store with a fixed clock.
Step 4: the server — src/server.ts
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { z } from "zod";
import { createRouter } from "./router.ts";
import { TaskStore } from "./store.ts";
const Env = z.object({ PORT: z.coerce.number().int().positive().default(3000) });
const { PORT } = Env.parse(process.env);
const handle = createRouter(new TaskStore());
async function readJson(req: IncomingMessage): Promise<unknown> {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk as Buffer);
const text = Buffer.concat(chunks).toString("utf8");
return text === "" ? undefined : (JSON.parse(text) as unknown);
}
function send(res: ServerResponse, status: number, body?: unknown): void {
if (body === undefined) {
res.writeHead(status).end();
return;
}
res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body));
}
const server = createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://localhost");
let body: unknown;
try {
body = await readJson(req);
} catch {
send(res, 400, { error: "Body must be valid JSON" });
return;
}
try {
const response = handle({ method: req.method ?? "GET", path: url.pathname, query: url.searchParams, body });
send(res, response.status, response.body);
} catch (error) {
console.error(error);
send(res, 500, { error: "Internal server error" });
}
});
server.listen(PORT, () => {
console.log(`Task board API on http://localhost:${PORT}`);
});This is the only file that deals with HTTP. It reads the body, turns invalid JSON into a 400, calls the router, and writes the response. It also validates PORT with Zod at start-up: PORT=abc npm start fails immediately with a clear message instead of misbehaving later.
Run it:
npm start # Task board API on http://localhost:3000
npm run dev # restarts on every change
npm run check # tsc: type-check everything, including the testsStep 5: tests — test/router.test.ts
import { beforeEach, describe, expect, it } from "vitest";
import { createRouter, type ApiRequest, type ApiResponse } from "../src/router.ts";
import type { Task } from "../src/schema.ts";
import { TaskStore } from "../src/store.ts";
let handle: (request: ApiRequest) => ApiResponse;
function call(method: string, url: string, body?: unknown): ApiResponse {
const { pathname, searchParams } = new URL(url, "http://test");
return handle({ method, path: pathname, query: searchParams, body });
}
beforeEach(() => {
handle = createRouter(new TaskStore(() => new Date("2026-12-04T10:00:00Z")));
});
describe("POST /tasks", () => {
it("creates a task with defaults", () => {
const res = call("POST", "/tasks", { title: " Write tests " });
expect(res.status).toBe(201);
expect(res.body).toMatchObject({ id: "1", title: "Write tests", priority: "medium", tags: [], done: false });
});
it("rejects invalid input with readable issues", () => {
const res = call("POST", "/tasks", { title: "", priority: "urgent" });
expect(res.status).toBe(400);
expect(res.body).toEqual({
error: "Validation failed",
issues: [
"title: Too small: expected string to have >=1 characters",
'priority: Invalid option: expected one of "low"|"medium"|"high"',
],
});
});
});
describe("GET /tasks", () => {
it("filters by done and priority", () => {
call("POST", "/tasks", { title: "A", priority: "high" });
call("POST", "/tasks", { title: "B", priority: "low" });
call("PATCH", "/tasks/1", { done: true });
const done = call("GET", "/tasks?done=true").body as Task[];
const low = call("GET", "/tasks?priority=low").body as Task[];
expect(done.map((t) => t.title)).toEqual(["A"]);
expect(low.map((t) => t.title)).toEqual(["B"]);
expect(call("GET", "/tasks?done=maybe").status).toBe(400);
});
});
describe("/tasks/:id", () => {
it("updates, reads and deletes a task", () => {
call("POST", "/tasks", { title: "Ship it" });
expect(call("PATCH", "/tasks/1", { done: true, tags: ["release"] }).body).toMatchObject({ done: true, tags: ["release"] });
expect(call("GET", "/tasks/1").status).toBe(200);
expect(call("DELETE", "/tasks/1").status).toBe(204);
expect(call("GET", "/tasks/1")).toEqual({ status: 404, body: { error: "Task 1 not found" } });
});
it("requires at least one field in a patch", () => {
call("POST", "/tasks", { title: "X" });
expect(call("PATCH", "/tasks/1", {}).status).toBe(400);
});
it("returns 404 and 405 for unknown routes and methods", () => {
expect(call("GET", "/nope").status).toBe(404);
expect(call("PUT", "/tasks").status).toBe(405);
});
});$ npm test
Test Files 1 passed (1)
Tests 6 passed (6)The tests drive the API through its real router with an in-memory store — no server, no ports, no mocks — so they run in milliseconds. A fresh store in beforeEach keeps every test independent.
How the course topics fit together
| Feature | Lessons |
|---|---|
Schemas → types with z.infer, unknown bodies |
Validating external data, any/unknown/never |
Task = NewTask & { … }, .partial() patches |
Intersection types, Utility types |
Task | undefined from the store |
null and undefined, Type narrowing |
TaskStore with #private fields |
Classes, Access modifiers |
safeParse results, route switch |
Discriminated unions, Union and literal types |
Imports with .ts, import type |
Modules |
PORT validation, node:http |
TypeScript with Node.js |
| Router tests with injected clock | Testing with Vitest |
Ideas for going further
- Persist tasks to a JSON file with
node:fs/promises, or to SQLite with the built-innode:sqlitemodule — onlystore.tschanges if you keep the same method signatures (define aninterface TaskRepositoryto make that explicit). - Add pagination to
GET /tasks(?page=2&pageSize=20) with a genericPage<T>response type. - Replace the hand-written router with Hono or Fastify, which type route params and bodies for you.
- Share the schemas with a React front end in a monorepo, so client and server validate the same way.
- Add linting with typescript-eslint and run
check,lintandtestin GitHub Actions.
Congratulations
You’ve gone from your first type annotation to a typed, validated, tested API. You can now read and write real TypeScript: model data precisely with unions and generics, keep untrusted data at the edges, derive types instead of duplicating them, and set up the tooling that keeps a codebase healthy.
Keep going: take a JavaScript project you already have and move it to TypeScript one file at a time. You’ll be surprised how many bugs the compiler finds on the way.
Add a statistics endpoint
Extend the finished API with GET /tasks/stats, returning { total, done, open, byPriority } where byPriority is a Record<Priority, number> with all three priorities (zero when there are none). Add a TaskStats type to schema.ts, a stats() method to TaskStore, and the route in the router — placed so that stats isn’t mistaken for a task id — with 405 for other methods. Write a Vitest test that creates three tasks (two high, one medium), completes one, and checks the exact response. npm run check and npm test must pass, and curl http://localhost:3000/tasks/stats should return the numbers.
// ---- src/schema.ts: add ----
export type TaskStats = {
// total, done, open, byPriority
};
// ---- src/store.ts: add a method to TaskStore ----
stats(): TaskStats {
// count the tasks
}
// ---- src/router.ts: add a route for GET /tasks/stats ----
// ---- test/router.test.ts: add a test ----// ---- src/schema.ts: add ----
export type TaskStats = {
total: number;
done: number;
open: number;
byPriority: Record<Priority, number>;
};
// ---- src/store.ts: import Priority and TaskStats, then add a method to TaskStore ----
stats(): TaskStats {
const byPriority: Record<Priority, number> = { low: 0, medium: 0, high: 0 };
let done = 0;
for (const task of this.#tasks.values()) {
byPriority[task.priority] += 1;
if (task.done) done += 1;
}
return { total: this.#tasks.size, done, open: this.#tasks.size - done, byPriority };
}
// ---- src/router.ts: add just before the "/tasks/:id" switch ----
// /tasks/stats — before /tasks/:id, so "stats" isn't treated as an id
if (id === "stats") {
return method === "GET" ? { status: 200, body: store.stats() } : error(405, "Method not allowed");
}
// ---- test/router.test.ts: add ----
describe("GET /tasks/stats", () => {
it("counts tasks by status and priority", () => {
call("POST", "/tasks", { title: "A", priority: "high" });
call("POST", "/tasks", { title: "B", priority: "high" });
call("POST", "/tasks", { title: "C" });
call("PATCH", "/tasks/2", { done: true });
expect(call("GET", "/tasks/stats")).toEqual({
status: 200,
body: { total: 3, done: 1, open: 2, byPriority: { low: 0, medium: 1, high: 2 } },
});
expect(call("POST", "/tasks/stats").status).toBe(405);
});
});Summary
- Zod schemas are the single source of truth: they validate requests and generate the TypeScript types.
- A pure
handle(request) → responserouter keeps HTTP details at the edge and makes every route testable without a network. - The store is a class with private
#fields and an injectable clock, so tests are deterministic. - Narrowing, discriminated results and
unknownrequest bodies keep untrusted data from leaking into typed code. - No build step: Node runs the TypeScript,
tscchecks it, Vitest tests it.