Express.js Customize the Error Page of JSON Errors

Assume that we are getting a request in JSON format and we don’t want to hit the default error page of express.json() middleware.

Instead we may want to send a specific JSON response back in case if JSON that we get is not valid.

We can check the body of requests with the following middleware.

// requestCheck.middleware.js
const requestCheckMiddleware = (err,req,res,next) => {
  if (res.headersSent) {
     next(err); 
     return;
  }
  if (req.body) {
    return res.status(400).json({ message:'Malformed JSON.' });
  }
}

module.exports = requestCheckMiddleware;

We can use that middleware globally or in our route exactly like that:

...
const requestCheckMiddleware = require('./requestCheck.middleware');
...
app.use(express.json());
//enable globally with app.use(requestCheckMiddleware) or use route based...
app.post('/post', requestCheckMiddleware, (req,res) => {
     res.json({ message: 'Body is a valid JSON.' });
});