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:
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:
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