Back to results for “JSON”
Node.js › Express & Middleware

What does the express.json() and express.urlencoded() built-in middleware do, and why must it be registered before routes that need to read req.body?

Intermediate

Answer

express.json() parses an incoming request body with a JSON content type into a JavaScript object, populating req.body; express.urlencoded() does the same for traditional HTML form submissions (application/x-www-form-urlencoded content type) -- both must be registered before any route that reads req.body, since Express processes middleware in registration order, and without this parsing step, req.body would remain undefined for any route handler that relies on it.
app.use(express.json()); // parses JSON bodies
app.use(express.urlencoded({ extended: true })); // parses form submissions

app.post('/users', (req, res) => {
  console.log(req.body); // only populated because the middleware above ran first
});
Real-world example A team debugging why req.body was always undefined in their POST route handlers discovers they'd forgotten to register express.json() at all, meaning Express never actually parsed the incoming JSON request body before it reached their route handler.

Common follow-ups: What happens if a client sends a JSON body but express.json() isn't registered -- does the request fail, or does req.body simply stay undefined?;What does the 'extended' option on express.urlencoded() actually control?