hoangvvo / next-connect

The TypeScript-ready, minimal router and middleware layer for Next.js, Micro, Vercel, or Node.js http/http2
https://www.npmjs.com/package/next-connect
MIT License
1.62k stars 65 forks source link

How can I access raw request body? #169

Closed lumenwrites closed 2 years ago

lumenwrites commented 2 years ago

Hi! I'm trying to set up Stripe webhooks in my app, and for them to work, they say:

Please note that you must pass the raw request body, exactly as received from Stripe, to the constructEvent() function; this will not work with a parsed (i.e., JSON) request body.

How can I access the "raw request body" if I'm using next-connect?

1aerostorm commented 2 years ago

Next-connect does not parses your req.body. Next.js does.

So, considering this, after your...

export default handler;

...add following:

export const config = {
  api: {
    bodyParser: false,
  },
}

Install micro library:

npm install micro

To get raw body do that:

import { buffer, } from 'micro';
...
// do it in each your route handler
// or create next-connect middleware and do it in middleware
const rawBody = (await buffer(req));
// if you want to parse it to string, use rawBody.toString();
// but you need directly send the rawBody (Buffer) to Stripe
lumenwrites commented 2 years ago

This worked perfectly!

Thank you so much for your help, it would've taken me forever to figure this out.