The independent file on technology, travel & lifeFrom Pakistan, for everywhere
Huzi Blogs.
The ArchiveSectionsSearch

Planning a trip? HTG Travels — flights, visas, hotels & Umrah, handled properly.

WhatsApp +92 317 5054959
Huzi Blogs.

An independent file on technology, travel and life — long-form guides written plainly, from Pakistan, for everywhere.

ShopMeet the Creator

Sections

  • Travel
  • Technology
  • Lifestyle
  • Programming
  • Sports
  • Linux
  • All sections

The Desk

  • The Archive
  • Search the file
  • Disclaimer & Data Privacy Policy
  • A project of huzi.pk

© 2026 blogs.huzi.pk — All rights reserved.

Set in Playfair Display & Inter

    HomeProgrammingStory
    Programming

    Building a REST API with Node.js and Express 5 (2026)

    H

    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 tsx in 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.

    Presented by

    HTG Travels — Plan the Trip, Skip the Runaround

    Flights, visas, Umrah packages and Hunza–Skardu tours, handled end to end from our licensed Sialkot desk. Real fares, hotel names in writing, and a human who answers — before you pay a rupee.

    Flights & rebooking Visa files Umrah 2026–27 Northern tours
    Visit huzi.pkWhatsApp +92 317 5054959

    Sialkot, Pakistan · Licensed agency · Fast quotes on WhatsApp


    You Might Also Like

    White Digital-Print Silk Party Dress – Emb Daman & 4-Side Border Dupatta

    White Digital-Print Silk Party Dress – Emb Daman & 4-Side Border Dupatta

    PKR 6300

    Luxury Heavy Embroidered Lawn Suit 3-Pc | Digital Print Silk Dupatta (2026 Collection)

    Luxury Heavy Embroidered Lawn Suit 3-Pc | Digital Print Silk Dupatta (2026 Collection)

    PKR 5750

    Heavy Embroidered Lawn 3-Piece Suit | Digital Print Diamond Dupatta (Unstitched Pakistan)

    Heavy Embroidered Lawn 3-Piece Suit | Digital Print Diamond Dupatta (Unstitched Pakistan)

    PKR 4600

    Heavy Embroidered Lawn Suit 3-Pc | Digital Print Diamond Zari Dupatta (2025)

    Heavy Embroidered Lawn Suit 3-Pc | Digital Print Diamond Zari Dupatta (2025)

    PKR 4750

    Unstitched 3-Piece Embroidered Lawn Suit | Sunflower Print, Digital Silk Dupatta (EID Collection)

    Unstitched 3-Piece Embroidered Lawn Suit | Sunflower Print, Digital Silk Dupatta (EID Collection)

    PKR 3800

    Keep reading

    Related files

    Programming
    English

    The Architecture of Scale: Building REST APIs with Node.js (2026)

    The design layer of a professional API: resource naming, honest status codes, layered architecture, Zod boundaries, argon2 hashing, and correlation-ID error handling.

    By HuziFile #85

    Read
    Programming
    English

    The Ultimate Beginner's Guide to Building a Website with Cloudflare Pages (2026)

    From an empty folder to a live site: git push, connect the repo in the dashboard, Pages Functions with D1 bindings, and the two fixes every beginner eventually needs.

    By HuziFile #99

    Read
    Programming
    English

    Real-Time Revolution: Building Interactive Apps with WebSockets (2026)

    The 101 Switching Protocols handshake, choosing between polling, SSE and WebSockets, a working Yjs editor server, and the scaling and security rules that keep the bridge standing.

    By HuziFile #87

    Read
    Programming
    English

    Introduction to GraphQL: A Modern Alternative to REST (2026)

    One endpoint, one query, exactly the fields you asked for: GraphQL's schema, queries, mutations and the 2026 @defer and @stream directives — and when REST is still the better call.

    By HuziFile #276

    Read
    Programming
    English

    Demystifying REST APIs: A Beginner's Guide (2026)

    Resources with URLs, HTTP verbs as actions, status codes as the contract, and where REST sits next to GraphQL and gRPC in a 2026 backend.

    By HuziFile #121

    Read
    Programming
    English

    The Beginner's Guide to React: Building the Modern Web (2026)

    The component mental model, one-way props, the server/client split that defines modern React, and the scaffolding commands to start a real project today.

    By HuziFile #52

    Read
    Back to the archive