`express.json`, `express.static`, `express.urlencoded`
Built-In Middleware
Three middlewares come pre-installed. Know what each one does and when to mount it.
What you'll learn
- Mount express.json
- Use express.urlencoded for forms
- Configure both for security
Express ships with three middleware factories: express.json,
express.urlencoded, express.static. (We covered static; this
lesson is about the body-parsing two.)
express.json — Parse JSON Bodies
app.use(express.json());
app.post("/api/users", (req, res) => {
console.log(req.body); // parsed JS object
res.status(201).end();
}); Sends with Content-Type: application/json → parsed into req.body.
Body Size Limit
app.use(express.json({ limit: "1mb" })); Default is 100KB. Raise if you have legitimate big payloads. Cap it always — an attacker sending a 5GB body would OOM your server.
Strict Mode
app.use(express.json({ strict: true })); // default strict: true (the default) only accepts JSON objects or arrays at
the top level. false accepts any JSON primitive. Keep the
default.
express.urlencoded — Form Submissions
app.use(express.urlencoded({ extended: true }));
app.post("/contact", (req, res) => {
console.log(req.body);
// <form action="/contact" method="POST">
// <input name="email" value="ada@example.com">
// </form>
// → { email: "ada@example.com" }
}); extended: true allows nested objects (a[b]=c) via the qs
library. extended: false uses querystring (flat keys only).
express.raw and express.text
Less common — raw bytes or plain text:
app.post("/webhooks/stripe",
express.raw({ type: "application/json" }),
(req, res) => {
// req.body is a Buffer — needed for signature verification
}
); For webhook endpoints you need raw bytes to verify HMAC
signatures — express.json() would already have parsed and lost
the exact bytes.
Order
Body parsers should mount before routes that read req.body:
app.use(express.json());
app.use("/api", apiRouter); // routes can now read req.body Mount Per Route Type
You don’t need both parsers globally. Mount what you actually expect:
app.use("/api", express.json({ limit: "100kb" }));
app.use("/contact", express.urlencoded({ extended: true })); Tighter limits, clearer intent.
Third-Party Middleware →