TExcelTAD
Home › Express & NestJS › Built-in Middleware

Built-in Middleware

Express 5 ships with five middleware factories. You'll use the first three in almost every project:

Middleware Handles Sets
express.json() bodies with Content-Type: application/json req.body = parsed object
express.urlencoded() HTML form posts (application/x-www-form-urlencoded) req.body = fields
express.static(dir) files in a folder sends the file, or calls next()
express.text() text/plain bodies req.body = string
express.raw() any body as bytes (e.g. webhooks that need the raw payload) req.body = Buffer

express.json()

The parser only acts when the request's Content-Type matches. Otherwise it leaves req.body untouched (undefined in Express 5):

node · try it yourself
const express = require('express');

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

app.post('/echo', (req, res) => {
  res.json({ received: req.body ?? null });
});

const server = app.listen(0, async () => {
  const url = `http://localhost:${server.address().port}/echo`;

  const asJson = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ title: 'Dune', pages: 412 }),
  });
  console.log('json body :', await asJson.text());

  const asText = await fetch(url, { method: 'POST', body: '{"title":"Dune"}' });
  console.log('no header :', await asText.text());
  server.close();
});
json body : {"received":{"title":"Dune","pages":412}}
no header : {"received":null}

fetch with a string body sends text/plain, so the JSON parser ignored it. Clients must send the right header.

Options worth knowing

Option Default Purpose
limit '100kb' reject larger bodies with 413 Payload Too Large
strict true only accept objects and arrays at the top level
type 'application/json' which content types to parse

Broken JSON

When the body isn't valid JSON, the parser calls next(err) with err.status === 400 and err.type === 'entity.parse.failed'. An error handler can turn that into a friendly reply:

node · try it yourself
const express = require('express');

const app = express();
app.use(express.json({ limit: '1kb' }));

app.post('/notes', (req, res) => res.status(201).json(req.body));

app.use((err, req, res, next) => {
  res.status(err.status ?? 500).json({ error: err.type ?? 'internal' });
});

const server = app.listen(0, async () => {
  const url = `http://localhost:${server.address().port}/notes`;
  const headers = { 'Content-Type': 'application/json' };

  const broken = await fetch(url, { method: 'POST', headers, body: '{"text": oops}' });
  console.log(broken.status, await broken.text());

  const huge = await fetch(url, { method: 'POST', headers, body: JSON.stringify({ text: 'x'.repeat(2000) }) });
  console.log(huge.status, await huge.text());
  server.close();
});
400 {"error":"entity.parse.failed"}
413 {"error":"entity.too.large"}

express.urlencoded()

HTML forms post name=Ana&age=31. The parser turns it into an object of strings. In Express 5 the extended option defaults to false (flat key/value pairs, no nested objects):

node · try it yourself
const express = require('express');

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

app.post('/signup', (req, res) => res.json(req.body));

const server = app.listen(0, async () => {
  const res = await fetch(`http://localhost:${server.address().port}/signup`, {
    method: 'POST',
    body: new URLSearchParams({ name: 'Ana', age: '31', newsletter: 'on' }),
  });
  console.log(await res.json());
  server.close();
});
{ name: 'Ana', age: '31', newsletter: 'on' }

fetch automatically sets Content-Type: application/x-www-form-urlencoded when the body is a URLSearchParams.

express.static()

Serve a folder of static assets — HTML, CSS, images, client JavaScript. If the file doesn't exist, it calls next() so your routes still work:

node · try it yourself
const express = require('express');
const fs = require('node:fs');
const path = require('node:path');

const publicDir = path.join(__dirname, 'public');
fs.mkdirSync(publicDir, { recursive: true });
fs.writeFileSync(path.join(publicDir, 'index.html'), '<h1>Home</h1>');
fs.writeFileSync(path.join(publicDir, 'app.css'), 'body { margin: 0 }');

const app = express();
app.use('/assets', express.static(publicDir, { maxAge: '1d' }));
app.get('/assets/hello', (req, res) => res.send('a route, not a file'));

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  for (const p of ['/assets/', '/assets/app.css', '/assets/hello', '/assets/missing.png']) {
    const res = await fetch(base + p);
    console.log(p.padEnd(19), res.status, (res.headers.get('content-type') ?? '-').padEnd(24), res.headers.get('cache-control') ?? '-');
  }
  server.close();
});
/assets/            200 text/html; charset=utf-8 public, max-age=86400
/assets/app.css     200 text/css; charset=utf-8  public, max-age=86400
/assets/hello       200 text/html; charset=utf-8 -
/assets/missing.png 404 text/html; charset=utf-8 -
Option Meaning
maxAge sets Cache-Control: max-age (ms or a string like '1d')
index file served for a directory (default index.html, false to disable)
dotfiles 'ignore' by default — .env is never served
fallthrough true: call next() on missing files

Tip: Always pass an absolute path (path.join(__dirname, 'public') or new URL('./public', import.meta.url)). A relative path is resolved against the directory you started Node from, which changes between machines.

Where to put parsers

Register parsers before the routes that need req.body. In big apps you can attach them only where needed: app.post('/upload', express.raw({ type: 'image/*' }), handler).

Test yourself

A client POSTs JSON text but forgets the Content-Type header. What is req.body after express.json()?

  1. The parsed object
  2. The raw string
  3. undefined
  4. An error is thrown

What status does express.json() produce for a body above its limit?

  1. 400
  2. 411
  3. 413
  4. 500

What does express.static do when the requested file does not exist (default options)?

  1. Responds 404 immediately
  2. Calls next() so later routes can handle it
  3. Serves index.html
  4. Throws an error