How to parse JSON body in Node.js
Parsing JSON request bodies is fundamental for creating REST APIs, handling form submissions, and processing client data in Node.js applications. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented JSON body parsing in numerous Node.js APIs for user data processing, configuration management, and dashboard data handling in enterprise applications. From my expertise, the most reliable approach is to use Express.js built-in JSON middleware. This method provides automatic parsing, error handling, and security features while supporting various content types and request sizes.
Use Express.js express.json()
middleware to automatically parse JSON request bodies.
const express = require('express')
const app = express()
// Parse JSON bodies with size limit and error handling
app.use(express.json({
limit: '10mb',
strict: true
}))
app.post('/api/users', (req, res) => {
const { name, email, age } = req.body
// Validate JSON data
if (!name || !email) {
return res.status(400).json({
error: 'Name and email are required'
})
}
// Process the JSON data
const user = { id: Date.now(), name, email, age }
res.status(201).json({
message: 'User created successfully',
user
})
})
// Error handling for invalid JSON
app.use((error, req, res, next) => {
if (error instanceof SyntaxError && error.status === 400 && 'body' in error) {
return res.status(400).json({ error: 'Invalid JSON' })
}
next()
})
The express.json()
middleware automatically parses incoming requests with JSON payloads and makes the parsed data available in req.body
. Configure options like limit
to set maximum request size, strict
to only accept arrays and objects, and verify
for custom validation. The middleware handles malformed JSON by throwing errors that can be caught with error handling middleware. Always validate the parsed JSON data before processing to ensure data integrity and security.
Best Practice Note:
This is the same approach we use in CoreUI backend APIs for secure and reliable JSON data processing.
Set appropriate size limits to prevent memory attacks, validate all incoming data with libraries like joi
or express-validator
, and implement proper error handling for malformed JSON and validation failures.