Express.js Basics
Routing, middleware, JSON APIs, and static files with Express.
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 itreq— the request, extended with goodies likereq.params,req.query, andreq.bodyres— the response, extended withres.json(),res.status(),res.send()
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 inreq.params.id - Query strings —
?page=2&sort=name; parsed automatically intoreq.query
Express matches routes in registration order and stops at the first match, so put specific routes before general ones.
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 requestapp.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.
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 intoreq.body(without it,req.bodyisundefined)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).
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.
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.cssError-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.)
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 questionsQuestion 1 of 5
Score: 0