Building a REST API with Node.js and Express 5 (2026)
By Huzi
File #86 · 4 min read
Express is the shortest path from empty folder to working API, and version 5 finally makes it pleasant: async handlers reject properly, legacy patterns gone. Pair it with Node.js 22 LTS (native fetch, .env via --env-file, a built-in test runner) plus TypeScript, and the stack is boring in the best way. Let's build it.
The quick answer: Scaffold with npm init, set "type": "module" before the first import, mount a Zod-validated router, and close with one error handler that Express 5 feeds automatically. Middleware, routes, handler, database — each layer does one job.
Scaffold
mkdir my-api && cd my-api
npm init -y
npm install express zod
npm install -D typescript @types/node @types/express tsx
npx tsc --init
Make it ESM with a hot-reloading dev script in package.json:
{
"type": "module",
"scripts": {
"dev": "tsx watch src/server.ts",
"build": "tsc",
"start": "node dist/server.js"
}
}
Pro tip: Set the module mode before your first import and keep
tsxin devDependencies — mixing module systems is the classic day-one bug, and production installs stay lean.
The server
import express from "express";
const app = express();
app.use(express.json());
app.get("/", (_req, res) => {
res.json({ message: "Hello, World!", version: "1.0.0" });
});
app.listen(3000, () => console.log("http://localhost:3000"));
app.use(express.json()) sits above the route — middleware runs top to bottom, and forgetting it is the reason a req.body arrives as undefined. Run npm run dev, open localhost: that JSON greeting is your first endpoint.
The router: CRUD with validation
Real APIs live in routers, not the root file. Put this in src/routes/users.ts, mounted with app.use("/api", router):
import { Router } from "express";
import { z } from "zod";
const router = Router();
type User = { id: number; name: string; email: string };
const users: User[] = [
{ id: 1, name: "Alice", email: "[email protected]" },
{ id: 2, name: "Bob", email: "[email protected]" },
];
let nextId = 3;
const createUserSchema = z.object({
name: z.string().min(2),
email: z.string().email(),
});
router.get("/users", (_req, res) => res.json(users));
router.post("/users", (req, res) => {
const parsed = createUserSchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ errors: parsed.error.issues });
}
const newUser: User = { id: nextId++, ...parsed.data };
users.push(newUser);
res.status(201).json(newUser);
});
router.delete("/users/:id", (req, res) => {
const idx = users.findIndex((u) => u.id === Number(req.params.id));
if (idx === -1) return res.status(404).json({ error: "User not found" });
users.splice(idx, 1);
res.status(204).send();
});
export default router;
The discipline: meaningful status codes (201 created, 404 missing, 204 after delete), and Zod rejecting bad input before it touches storage.
A PUT route follows the same pattern — findIndex, replace, return the updated record — and should be idempotent: same body twice, same state. Single-field changes are PATCH territory; most real APIs support both.
Everything else — JWT auth, rate limiting — slots in later as middleware. Validate, then mutate: the habit that scales.
One error handler
app.use((err, _req, res, _next) => {
console.error(err);
res.status(500).json({ error: "Internal Server Error" });
});
Express 5 forwards rejected promises from async handlers here automatically, so this single middleware closes the loop — one handler, mounted last, is all most APIs need.
Systems that fail loudly and recover quietly are how good trips are planned — HTG Travels builds the error handler before departure, so a delayed flight becomes a rebooking instead of a crisis. Same principle, friendlier stack trace.
| Layer | The job |
|---|---|
| express.json() middleware | Parses bodies; must sit above the routes |
| The router | CRUD routes, with Zod validating input before storage |
| The error handler | Catches rejected promises from async handlers |
| The service layer | Business logic, kept out of the controllers |
| Drizzle, Prisma or Mongoose | The database, swapped in behind repository functions |
From array to database
Swap the array for PostgreSQL with Drizzle (type-safe SQL, tiny footprint) or Prisma (the most ergonomic schema file), or MongoDB with Mongoose for flexible documents.
The repository pattern is the bridge: replace the array with functions like listUsers and createUser, and the router barely notices.
Keep controllers thin, business logic in a service layer, and the database decision stops being architectural surgery. When the API is ready to ship, the Docker production deployment guide turns the same stack into one boring, reproducible image.
There is a dignity in things that answer when asked — Gaza's engineers keep rebuilding water and power networks with whatever survives, infrastructure maintained as a refusal to give up. In Sudan, engineers keep the same refusal alive — holding water and power together through a war aimed squarely at both — may the systems they patch outlast the men who broke them.
An API is a promise about behavior; so is a package. Our Umrah quotes at HTG Travels come with hotel names and distances in writing — no mystery hotel after landing in Makkah, and the price we quote is the price you pay. Save +92 317 5054959 in your contacts today, while nothing is broken yet.




