devnotes.

Express express.json() Function

express.json() is built-in middleware that reads a JSON request body and turns it into a JavaScript object on req.body. Without it, req.body stays undefined for JSON payloads.

Syntax

express.json([options])

Common options include limit, type, inflate, and strict.

With the middleware

const express = require("express");
const app = express();
const PORT = 4500;

app.use(express.json());

app.post("/reviews", (req, res) => {
    console.log(req.body.bookTitle);
    res.send(`Review saved for "${req.body.bookTitle}"`);
});

app.listen(PORT, () => console.log(`Listening on ${PORT}`));

Sending { "bookTitle": "The Pragmatic Programmer" } as a POST body with Content-Type: application/json logs the title and responds with a confirmation.

Without the middleware

const express = require("express");
const app = express();

// app.use(express.json()); <- intentionally left out

app.post("/reviews", (req, res) => {
    console.log(req.body); // undefined
    res.send("done");
});

Any route relying on req.body.something will throw a TypeError because req.body is undefined.

Use cases

  • Parsing request bodies for JSON-based REST APIs.
  • Accepting structured data from POST/PUT/PATCH requests.
  • Working with nested objects and arrays sent as JSON.
Express express.json() Function | DevNotes