← Back to the Build Your Homepage series
🟒
EPISODE 04
routing Β· middleware Β· JSON parser Β· static files

Express.js

Build real HTTP servers fast with Express. Learn routing, middleware composition, JSON body parsing, and serving static files.

ExpressroutingmiddlewareREST
Duration
⏱ About 2 hours
Level
πŸ“Š Intermediate
Prerequisite
🎯 node-03
OUTCOME
An Express server with multiple routes, middleware, and static assets

What you'll learn

  • 1Set up an Express app and route handlers
  • 2Use built-in JSON and static middleware
  • 3Write custom middleware (logging, auth check)
  • 4Handle errors centrally

1. Hello, Express

bash
npm install express
javascript
import express from "express";
const app = express();

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

app.get("/api/hello/:name", (req, res) => {
  res.json({ message: `Hello, ${req.params.name}!` });
});

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

2. Middleware

javascript
// Built-in: parse JSON bodies
app.use(express.json());

// Built-in: serve files from /public
app.use(express.static("public"));

// Custom: log every request
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

Middleware runs in the order it is registered. Always call next() unless you send a response.

3. Route Methods

javascript
app.post("/users", (req, res) => {
  const user = req.body;       // populated by express.json()
  // ... save to database ...
  res.status(201).json(user);
});

app.put("/users/:id", (req, res) => { /* ... */ });
app.delete("/users/:id", (req, res) => { /* ... */ });

4. Error Handling

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

// Error middleware (4 args!)
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: "Internal server error" });
});
⚠️

Error middleware must have 4 parameters (err, req, res, next) β€” that signature is how Express recognizes it.

Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub β†—