/

How to Retrieve Both Parsed Body and Raw Body in Express

How to Retrieve Both Parsed Body and Raw Body in Express

Learn how to retrieve both the parsed body and raw body in Express using the body-parser middleware.

In a recent application I developed, I encountered a specific challenge. While working with Express, I successfully imported the body-parser module to parse the body as JSON:

1
2
import bodyParser from 'body-parser'
app.use(bodyParser.json())

However, when integrating with the Stripe payments API, I needed access to the raw body without parsing it, while still being able to parse the body as JSON.

To achieve this, I used the following method:

1
2
3
4
5
app.use(bodyParser.json({
verify: (req, res, buf) => {
req.rawBody = buf
}
}))

By adding the verify property as a callback function to the body-parser.json() middleware, I was able to store the raw body in req.rawBody. Furthermore, the parsed JSON data remains accessible through req.body.

Although this approach mentioned on the body-parser GitHub page increases the RAM usage for each request, it was necessary for my specific requirements. Alternatively, I could have considered creating a separate server solely for handling the Stripe webhook.

By implementing this solution, we can effectively retrieve both the parsed body and raw body in Express.

Tags: Express, body-parser, middleware, Stripe, JSON, raw body