node.jsexpressbody-parser

Nodejs bodyParser.raw on one route


I have the following in my index.js:

app.use(bodyParser.json());

But Stripe webhooks want this:

Match the raw body to content type application/json

If I change my index.js to the following:

app.use(bodyParser.raw({type: 'application/json'}));

It works fine. But all my other API routes will not work anymore. Here is my route:

router.route('/stripe-events')
  .post(odoraCtrl.stripeEvents)

How can I change to the raw body for only this api route?


Solution

  • You can access to both at the same time by doing this:

    app.use(bodyParser.json({
      verify: (req, res, buf) => {
        req.rawBody = buf
      }
    }))
    

    Now the raw body is available on req.rawBody and the JSON parsed data is available on req.body.