All academies

Express.js Basics

Routing, middleware, JSON APIs, and static files with Express.

22 minLevel 14 of 20

From http to Express

In the last lesson you routed requests with if/else chains, parsed bodies by collecting chunks, and set JSON headers by hand. Express is a thin framework over the http module that does all of that for you. It has been the most popular Node web framework for over a decade.

Install it with npm install express. The core objects:

  • app — your application; you register routes and middleware on it
  • req — the request, extended with goodies like req.params, req.query, and req.body
  • res — the response, extended with res.json(), res.status(), res.send()
Hello, Express
const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.send("Hello from Express!");
});

app.listen(3000, () => {
  console.log("Server on http://localhost:3000");
});

Routing: methods, params, and queries

Routes pair an HTTP method with a path pattern: app.get, app.post, app.put, app.delete. Two kinds of dynamic input:

  • Route parameters — named segments like /users/:id; values appear in req.params.id
  • Query strings — ?page=2&sort=name; parsed automatically into req.query

Express matches routes in registration order and stops at the first match, so put specific routes before general ones.

Params and queries
const express = require("express");
const app = express();

// GET /users/42  ->  req.params.id === "42"
app.get("/users/:id", (req, res) => {
  res.json({ userId: req.params.id });
});

// GET /search?q=node&page=2  ->  req.query
app.get("/search", (req, res) => {
  const { q, page = "1" } = req.query;
  res.json({ query: q, page: Number(page) });
});

app.listen(3000);

Middleware: the heart of Express

A middleware is a function (req, res, next) that runs before your route handlers. Each middleware can inspect or modify req and res, then either end the response or call next() to pass control down the chain. An Express app is really just a pipeline of middleware ending in a route handler.

  • app.use(fn) — run for every request
  • app.use("/admin", fn) — run only for paths starting with /admin
  • Common uses: logging, authentication, body parsing, CORS headers

Forgetting to call next() (without ending the response) is the classic Express bug — the request hangs forever.

A logger and a guard
const express = require("express");
const app = express();

// Runs for EVERY request:
app.use((req, res, next) => {
  console.log(req.method + " " + req.url);
  next(); // pass control onward - do not forget!
});

// Runs only under /admin - and may reject:
app.use("/admin", (req, res, next) => {
  if (req.headers["x-api-key"] !== "secret") {
    return res.status(401).json({ error: "Unauthorized" });
  }
  next();
});

app.get("/admin/stats", (req, res) => res.json({ users: 42 }));
app.listen(3000);

Building a JSON API

For APIs, two pieces do the heavy lifting:

  • express.json() — built-in middleware that parses JSON request bodies into req.body (without it, req.body is undefined)
  • res.status(code).json(obj) — sets the status, serializes the object, and sets the Content-Type header in one chain

A RESTful resource maps naturally onto routes: GET the collection, GET one by id, POST to create (respond 201), PUT to update, DELETE to remove (respond 204).

A tiny in-memory API
const express = require("express");
const app = express();

app.use(express.json()); // enables req.body for JSON

let todos = [{ id: 1, text: "learn Express", done: false }];

app.get("/todos", (req, res) => res.json(todos));

app.post("/todos", (req, res) => {
  if (!req.body.text) {
    return res.status(400).json({ error: "text is required" });
  }
  const todo = { id: todos.length + 1, text: req.body.text, done: false };
  todos.push(todo);
  res.status(201).json(todo);
});

app.delete("/todos/:id", (req, res) => {
  todos = todos.filter((t) => t.id !== Number(req.params.id));
  res.status(204).end();
});

app.listen(3000);

Serving static files

express.static(folder) serves files straight from a directory — HTML, CSS, images, client-side JavaScript. A request for /style.css returns public/style.css if it exists; otherwise Express moves on to the next route.

Mount it under a prefix to namespace your assets: app.use("/assets", express.static("public")) maps /assets/logo.png to public/logo.png. Build the folder path with path.join(__dirname, "public") so it works no matter where the process starts.

Static assets plus an API
const express = require("express");
const path = require("path");
const app = express();

// Serve everything in ./public at the site root:
app.use(express.static(path.join(__dirname, "public")));

// API routes still work alongside:
app.get("/api/health", (req, res) => res.json({ ok: true }));

app.listen(3000);
// GET /index.html  -> public/index.html
// GET /css/app.css -> public/css/app.css

Error-handling middleware

Express recognizes a special middleware signature with four parameters: (err, req, res, next). Register it last, after all routes. Any synchronous throw, or any call to next(err), skips the remaining normal middleware and jumps straight to it — one place to log errors and shape error responses.

In Express 4, errors inside async handlers must be caught and forwarded manually with next(err) — a rejected promise alone won't reach the error middleware. (Express 5 forwards rejected promises automatically.)

Centralized error handling
const express = require("express");
const app = express();

app.get("/boom", (req, res) => {
  throw new Error("something broke"); // sync throw - caught by Express
});

app.get("/async-boom", async (req, res, next) => {
  try {
    await Promise.reject(new Error("async failure"));
  } catch (err) {
    next(err); // forward async errors explicitly (Express 4)
  }
});

// FOUR params mark this as the error handler. Register it LAST:
app.use((err, req, res, next) => {
  console.error("Error:", err.message);
  res.status(500).json({ error: "Internal Server Error" });
});

app.listen(3000);

Check your understanding

5 questions

Question 1 of 5

Score: 0

Multiple choice

For the route app.get("/books/:isbn", ...), where is the isbn value for a request to /books/978?