Skip to content

Express 5 for Beginners: Routes, Params, Query, JSON Bodies, Middleware and Error Handling

NeedMyTools Academy

Sign in free to read the full lesson

Sign in or create a free account

Free forever. No card, no paywall.

In the previous lesson every route was an if on method and path, every answer needed writeHead and JSON.stringify, and reading a body took a helper function. Express is the most used web framework for Node.js and removes that repetition. Express 5, released as stable in 2024, also passes errors from async routes to your error handler by itself. In this lesson you build a product API for a small spice shop, add middleware that logs every request with its timing, and see a real problem we hit: Express sent a full stack trace, with folder paths, to the client. Then you fix it with an error handler. Recorded with Express 5.3.0 on Node.js 22.23.4.

Quick answer

Install with npm install express, create const app = express(), and add app.use(express.json()) so req.body holds parsed JSON. Define routes with app.get, app.post, app.patch and app.delete, read :id style parts from req.params and the query string from req.query, and answer with res.status(code).json(data). Middleware is a function (req, res, next) that runs in the order you add it. Put a 404 handler after all routes and a four argument error handler (err, req, res, next) last.

40 min read and practice · Content checked on 28 November 2026

In this lesson you will

  • Build GET and POST routes with params, query strings and JSON bodies
  • Write middleware and explain why its order matters
  • Add a 404 handler and an error handler that hides internal details

Installing Express and the first routes

Express is a package, so the project needs a package.json with "type": "module" and an npm install express. Installing it added 65 packages, because Express itself depends on small libraries for parsing bodies, cookies and paths. Commit package.json and package-lock.json, and leave node_modules out of Git as you learned in the modules lesson.

Each route names a method and a path pattern. /api/products/:id matches /api/products/3 and puts "3" in req.params.id, always as text, so the code converts it with Number before comparing with the numeric ids. Query values such as ?max=50 land in req.query, also as text. res.json(data) sets the JSON content type and stringifies for you, and res.status(404) sets the code first, so a whole answer fits on one line.

Without app.use(express.json()), req.body is undefined in Express 5 and destructuring it throws. That is why the POST route reads req.body ?? {}: a request with no body or the wrong content type gets a clean 400 instead of a crash. The last app.use with no path catches any request no route answered, so a typo like /api/prodcts returns JSON with 404 rather than an HTML page.

Example: A product API in Express
app.js
import express from "express";

const app = express();
app.use(express.json());

// Middleware: runs for every request, then hands over with next()
app.use((req, res, next) => {
  const start = Date.now();
  res.on("finish", () => {
    console.log(`${req.method} ${req.url} ${res.statusCode} ${Date.now() - start}ms`);
  });
  next();
});

const products = [
  { id: 1, name: "Saffron 5 g", price: 38 },
  { id: 2, name: "Dates 1 kg", price: 45 },
  { id: 3, name: "Oud oil 3 ml", price: 120 },
];

app.get("/api/products", (req, res) => {
  const max = Number(req.query.max ?? Infinity);
  res.json(products.filter((p) => p.price <= max));
});

app.get("/api/products/:id", (req, res) => {
  const product = products.find((p) => p.id === Number(req.params.id));
  if (!product) return res.status(404).json({ error: "No product with that id" });
  res.json(product);
});

app.post("/api/products", (req, res) => {
  const { name, price } = req.body ?? {};
  if (typeof name !== "string" || typeof price !== "number") {
    return res.status(400).json({ error: "name (text) and price (number) are required" });
  }
  const product = { id: products.length + 1, name, price };
  products.push(product);
  res.status(201).json(product);
});

app.use((req, res) => {
  res.status(404).json({ error: "Not found" });
});

app.listen(3000, () => console.log("Listening on http://localhost:3000"));
Real output: terminal, npm install express (in a folder with "type": "module")
added 65 packages, and audited 66 packages in 4s

31 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
Real output: eight curl requests against node app.js (status code shown after errors)
$ curl .../api/products
[{"id":1,"name":"Saffron 5 g","price":38},{"id":2,"name":"Dates 1 kg","price":45},{"id":3,"name":"Oud oil 3 ml","price":120}]
$ curl ".../api/products?max=50"
[{"id":1,"name":"Saffron 5 g","price":38},{"id":2,"name":"Dates 1 kg","price":45}]
$ curl .../api/products/3
{"id":3,"name":"Oud oil 3 ml","price":120}
$ curl .../api/products/9
{"error":"No product with that id"} 404
$ curl -X POST .../api/products -H "Content-Type: application/json" -d '{"name":"Arabic coffee 250 g","price":32}'
{"id":4,"name":"Arabic coffee 250 g","price":32} 201
$ curl -X POST .../api/products -H "Content-Type: application/json" -d '{"name":"Rose water"}'
{"error":"name (text) and price (number) are required"} 400
$ curl .../api/prodcts
{"error":"Not found"} 404
Real output: the server terminal, printed by the logging middleware
Listening on http://localhost:3000
GET /api/products 200 4ms
GET /api/products?max=50 200 1ms
GET /api/products/3 200 0ms
GET /api/products/9 404 0ms
POST /api/products 201 1ms
POST /api/products 400 1ms
GET /api/prodcts 404 1ms

The URL is shortened to ... for http://localhost:3000. One request is missing from these two lists on purpose: the broken JSON body, shown in the next section.

Sign in free to read the full lesson

You are reading the free preview. Create a free account (it takes one minute, no password) to unlock the rest of this lesson and track your progress.

Unlocks after sign-in:

  • 2 more sections with live code examples
  • Common mistakes to avoid
  • Hands-on coding exercise with automatic checks
  • Practice quiz and the graded lesson test
Sign in or create a free account

Free forever. No card, no paywall.

Questions people ask

Is Express still worth learning?

Yes. It is the most downloaded Node.js web framework, Express 5 is actively maintained, and newer frameworks such as Fastify and Hono use the same ideas of routes, middleware and handlers, so the skills carry over.

What changed in Express 5 compared to Express 4?

The biggest change for beginners is that errors from async handlers reach your error handler without extra code. Express 5 also needs Node.js 18 or newer, removed old deprecated methods, and changed some path pattern syntax, so check the migration guide when you upgrade an old app.

How do I split Express routes into several files?

Create const router = express.Router() in a file such as routes/products.js, add routes to it with router.get(...), export it, and mount it with app.use("/api/products", router). Paths inside the router are then relative, such as "/:id".

Should I remove the X-Powered-By header?

It is a good small habit. Express adds X-Powered-By: Express to every response, which tells scanners what you run. app.disable("x-powered-by") removes it, and the Express security guide lists further steps such as the helmet package.

How do I allow my front end on another domain to call the API?

Browsers block cross origin requests unless the server sends CORS headers. Install the cors package and allow only your own front end, for example cors({ origin: "https://shop.example" }), rather than every origin.

Sources

Facts in this lesson were checked against these official pages on 28 November 2026.

Code examples stay in English and run in a sandbox on your device. If you spot a mistake, tell us through the contact page.