Next.js Discord

Discord Forum

How to get rawBody?

Answered
Artois Hound posted this in #help-forum
Open in Discord
Avatar
Artois HoundOP
I had a working code setup to get the rawBody from import { NextApiRequest, NextApiResponse } from "next";

but now that import type { NextApiRequest, NextApiResponse } from 'next/types' is enforced, I just can't figure out how to get the raw body from it.

my previous solution was
let rawBody = Buffer.alloc(0)

    for await (const chunk of req) {
      rawBody = Buffer.concat([rawBody, chunk])
    }


with the bodyParser turned off
export const config = {
  api: {
    bodyParser: false
  }
}
Answered by nehalist
there's also a blog post that does that manually: https://vancelucas.com/blog/how-to-access-raw-body-data-with-next-js/
View full answer

11 Replies

Avatar
what about request.text() within the route handler function?
Avatar
Artois HoundOP
Property 'text' does not exist on type 'NextApiRequest'.ts(2339)
Avatar
what nextjs version are you using?
Avatar
Artois HoundOP
14.2.4
Avatar
according to the docs the type of request in route handlers should be Request, not NextApiRequest:

 
export async function GET(request: Request) {
  const rawBody = await request.text();
Avatar
Artois HoundOP
I am using Pages Directory https://nextjs.org/docs/pages/building-your-application/routing/api-routes

and it says
import type { NextApiRequest, NextApiResponse } from 'next'
as
export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
)
Avatar
didn't know that. my knowledge with pages router is a bit out of date, but according to the docs https://www.npmjs.com/package/raw-body might be a solution
Avatar
there's also a blog post that does that manually: https://vancelucas.com/blog/how-to-access-raw-body-data-with-next-js/
Answer
Avatar
Artois HoundOP
Nevermind, this works.
I tried it before, but I messed something up, but on a second run it's great.
Thanks m8 @nehalist šŸ™‚