How to Fix JSON Parse Error in Express Quickly
JSON parse error in Express, ensure you use the built-in express.json() middleware to parse incoming JSON requests. Also, handle errors gracefully by adding error-handling middleware to catch invalid JSON payloads.Why This Happens
This error happens because Express tries to read JSON data from the request body but fails when the JSON is malformed or when the server lacks the proper middleware to parse JSON. Without express.json(), Express cannot understand the JSON format, causing a parse error.
import express from 'express'; const app = express(); app.post('/data', (req, res) => { // Trying to access req.body without JSON parser res.send(req.body); }); app.listen(3000);
The Fix
Add the express.json() middleware before your routes to parse JSON bodies correctly. This middleware reads the JSON string and converts it into a JavaScript object accessible via req.body. Also, add error-handling middleware to catch and respond to invalid JSON errors gracefully.
import express from 'express'; const app = express(); // Middleware to parse JSON app.use(express.json()); app.post('/data', (req, res) => { res.send({ received: req.body }); }); // Error handling middleware for JSON parse errors app.use((err, req, res, next) => { if (err instanceof SyntaxError && err.status === 400 && 'body' in err) { return res.status(400).send({ error: 'Invalid JSON' }); } next(err); }); app.listen(3000);
Prevention
Always use express.json() middleware for routes expecting JSON input. Validate JSON on the client side before sending. Use error-handling middleware to catch malformed JSON and respond with clear messages. Consider using tools like linters or API testing tools to check JSON format before requests.
Related Errors
Other common errors include Payload Too Large when JSON is too big, fixed by setting limit in express.json(). Also, TypeError: req.body is undefined happens if JSON middleware is missing. Always check middleware order and request headers.