Express res.json() Method
What you’ll learn
- How to return API responses with
res.json(). - How to combine status codes and JSON payloads.
- How to structure success and error response bodies.
- How to avoid duplicate sends in async code paths.
Syntax
javascript
res.json(body)
res.status(200).json(body)1
Send a basic JSON payload
javascript
app.get('/api/ping', function (req, res) {
res.json({ ok: true, message: 'pong' });
});2
Set status code and return JSON
javascript
app.post('/api/users', function (req, res) {
var user = { id: 101, name: req.body.name };
res.status(201).json({ message: 'User created', data: user });
});3
Return consistent JSON error response
javascript
app.get('/api/orders/:id', function (req, res) {
if (!/^\d+$/.test(req.params.id)) {
return res.status(400).json({ error: 'Invalid order id' });
}
res.json({ id: Number(req.params.id), status: 'processing' });
});⚠️ Common pitfalls
- Do not call multiple response methods after
res.json(); the response is already committed. - Use clear and consistent response shapes across endpoints.
- Return early after error responses to avoid accidental extra writes.
❓ FAQ
It converts the given value to JSON and sends it in the HTTP response with the correct content type.
Yes, chain status first like res.status(201).json(data).
For API payloads, res.json() is preferred because it makes JSON intent explicit.
Yes, it handles objects, arrays, booleans, numbers, and null.
Sending multiple responses from one request path, especially in async branches.
Did you know?
res.json() automatically serializes JavaScript values and sends them with a JSON content type.
4 people found this page helpful
