0
0
ExpressDebug / FixBeginner · 4 min read

How to Fix JSON Parse Error in Express Quickly

To fix a 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.

javascript
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);
Output
SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at parse (body-parser.js:...)
🔧

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.

javascript
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);
Output
{"received":{"name":"Alice","age":30}}
🛡️

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.

Key Takeaways

Use express.json() middleware to parse JSON request bodies.
Add error-handling middleware to catch and respond to invalid JSON.
Validate JSON format on client side before sending requests.
Set size limits in express.json() to avoid payload too large errors.
Middleware order matters: place express.json() before routes.