Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 43 ยท Middleware

Built-in Middleware

Learn the middleware that ships with Express: express.json, urlencoded, text, raw and static, their limits, and why req.body is undefined in Express 5 without a parser.

Express itself includes only a handful of middleware functions, and they cover the jobs nearly every app needs: reading request bodies and serving files. Everything else (logging, security headers, sessions) comes from separate npm packages, which we meet in the next lesson.

Reading a request body is the best example of why middleware exists. Node hands you the body as a stream of chunks that you must collect, join and decode. A body parser does that once, in one place, and puts the result on req.body so every later handler can simply read it. If you have not seen streams yet, the Node.js streams lessons show what a request body really is.

All real Express code in this lesson is read-only; the runnable examples are a hand-written body parser on our stand-in framework so you can watch the mechanism.

express.json()

express.json() parses bodies whose Content-Type is application/json:

JavaScript
import express from 'express';

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

app.post('/notes', (req, res) => {
  const { title } = req.body;
  res.status(201).json({ saved: title });
});

It must be registered before the routes that read req.body, because middleware runs in order. Its useful options:

JavaScript
app.use(express.json({
  limit: '1mb',        // default is '100kb'
  strict: true,        // only accept objects and arrays (default)
  type: 'application/json', // which Content-Types to parse
}));

If the body is bigger than limit, the parser answers 413 Payload Too Large before your handler runs. If the JSON is malformed, it passes a 400 error to your error handler. Both come from the parser, not from your code, so a missing error handler shows Express's default error page.

Four body parsers

express.json application/json into an object.
express.urlencoded HTML form posts into an object.
express.text Plain text into a string.
express.raw Any bytes into a Buffer.

Each one only touches bodies with a matching Content-Type.

1 / 2

req.body is undefined in Express 5

In Express 4, req.body was always at least an empty object {}. In Express 5 it is undefined until a parser sets it, and a parser leaves it undefined when the request has no body or the wrong Content-Type. That means this common line can crash:

JavaScript
app.post('/notes', (req, res) => {
  const { title } = req.body; // TypeError if req.body is undefined
});

Defend against it with a default or a check:

JavaScript
const { title } = req.body ?? {};
if (!title) return res.status(400).json({ error: 'title is required' });

Real validation is the topic of Validating Input.

How a body parser works

Here is a stand-in jsonBody middleware. It does what express.json() does in spirit: only act when the Content-Type is JSON, collect the chunks, enforce a size limit, parse, and either set req.body or forward an error.

Node.js A hand-written JSON body parser

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Four outcomes appear: a normal save, a 400 for broken JSON, a 413 for a body over the limit, and, for a request without a JSON content type, req.body stays undefined so the handler's own check answers 400. Real express.json() has more features (gzip request bodies, charset checks, verify hooks) but the flow is the same.

express.urlencoded()

HTML forms posted the traditional way send application/x-www-form-urlencoded, which looks like name=Ada&age=36. Parse it with:

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

In Express 5 extended defaults to false, which uses the simple built-in parser and gives flat string values. Set extended: true only if you need nested form fields such as user[name]=Ada; that uses the qs library. Notice every value arrives as a string, including numbers. Forms, Redirects and Flash Messages builds on this.

Node.js Parsing form data (urlencoded)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The age comes in as the string "36"; convert it yourself with Number(...).

express.text() and express.raw()

Two smaller parsers cover other content types:

JavaScript
app.use('/webhooks/text', express.text({ type: 'text/plain' }));    // req.body is a string
app.use('/webhooks/stripe', express.raw({ type: 'application/json' })); // req.body is a Buffer

express.raw() is what you need when you must keep the exact bytes, for example to verify a webhook signature, because parsing and re-serializing JSON would change the bytes. For that route you register express.raw() instead of express.json(), not in addition to it.

express.static()

express.static(folder) serves files from a directory:

JavaScript
import path from 'node:path';

app.use(express.static('public'));                     // /logo.png -> public/logo.png
app.use('/assets', express.static('public', {
  maxAge: '1d',        // Cache-Control max-age
  index: 'index.html', // served for a folder URL
  extensions: ['html'],// /about -> about.html
}));

It sends the right content type, ETag, Last-Modified and handles range requests. If no file matches it calls next(), so later routes still get a chance. Dotfiles such as .env are ignored by default, but keep secrets outside the served folder anyway. Relative paths resolve against the process's working directory, so prefer path.join(import.meta.dirname, 'public'). Static serving is covered further in Static Files, Downloads and Streaming.

Mount express.static early so static files skip your other middleware, but after anything that must see every request, such as a request logger.

What is real and what is the stand-in

express.json, urlencoded, text, raw and static, with the options and defaults above, are real Express 5 (backed by the body-parser and serve-static packages). The runnable parsers are simplified: they skip charset handling, compression and the full error shapes. They exist to show the collect-and-parse mechanism, not to replace the real ones.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In Express 5, what is req.body for a POST request when no body parser is registered?

    Express 4 gave an empty object, but Express 5 leaves req.body undefined until a parser sets it.
  2. 2. Which middleware turns a JSON request body into a JavaScript object?

    express.json() parses bodies with an application/json Content-Type and sets req.body.
  3. 3. A client posts a 2 MB JSON body to an app that uses express.json() with default options. What is the likely response?

    The default limit is 100kb. Larger bodies are rejected with 413 before your handler runs.
  4. 4. Why would you use express.raw() for a webhook route?

    Re-serializing parsed JSON can change the bytes, so signature checks need the untouched Buffer.
  5. 5. Why must express.json() be registered before the routes that use req.body?

    If the route comes first, it runs before the parser has set req.body.

Summary

  • Express ships json, urlencoded, text, raw and static; the rest is third-party.
  • Body parsers collect the request stream and set req.body; register them above your routes.
  • In Express 5, req.body is undefined when nothing was parsed, so default it (?? {}) and validate.
  • The default JSON limit is 100kb; oversized bodies get 413, bad JSON gets 400.
  • urlencoded gives string values; extended is false by default in Express 5.
  • express.static serves a folder and falls through to later routes when no file matches.

Next: Common Third-Party Middleware.