Lesson 20 +10 XP

Built-in Middleware (express.json, urlencoded, static)

Essential Built-in Middleware

Modern Express comes with essential built-in middleware functions for request body parsing and static file serving.

1. express.json(): Parsing JSON Payloads

Parses incoming requests with JSON payloads (Header Content-Type: application/json) and populates req.body.

app.use(express.json({ limit: "1mb" }));

2. express.urlencoded(): Parsing HTML Form Submissions

Parses incoming requests with URL-encoded payloads from HTML forms (Content-Type: application/x-www-form-urlencoded).

app.use(express.urlencoded({ extended: true }));

3. express.static(): Serving Static Assets

Serves static files such as HTML, CSS, JavaScript files, and images from a designated directory.

const path = require("node:path");

// Serve assets from public directory at root path
app.use(express.static(path.join(__dirname, "public")));

// Serve assets under virtual prefix path
app.use("/assets", express.static(path.join(__dirname, "public")));

TL;DR

  • Always call app.use(express.json()) near top of server setup to parse JSON bodies into req.body.
  • Use express.static() to serve static public uploads and static web files.