Express comes with built-in middleware for common tasks.
express.json()
This middleware parses incoming JSON data and makes it available in req.body.
This is essential for handling POST, PUT, and PATCH requests. We’ll cover these request types in detail in the next lesson, but we’re explaining this middleware now so you understand what it’s doing whenever you see it in code examples or tutorials.
app.use(express.json());
Note: Unlike our custom middleware, we don’t need to call next() with built-in middleware like express.json(). These middleware functions automatically call next() for us after they finish processing.
Why we need it
- When clients send JSON data, it comes as a string
express.json()converts it to a JavaScript object- Without it,
req.bodywould be undefined
Example
app.use(express.json());
app.post("/users", (req, res) => {
console.log(req.body);
res.json({ message: "User created" });
});
When a client sends JSON data like { "name": "John", "email": "john@example.com" }, the express.json() middleware will parse it and make it available in req.body as a JavaScript object.
For example, if a client sends this from the frontend:
{
"name": "John",
"email": "john@example.com"
}
Then req.body will contain:
{
name: "John",
email: "john@example.com"
}
You can then access the values in your route:
app.post("/users", (req, res) => {
const { name, email } = req.body;
console.log(name); // "John"
console.log(email); // "john@example.com"
res.json({ message: "User created" });
});
What happens without express.json()
Without the middleware, req.body would be undefined, and you wouldn’t be able to access the data sent by the client.