How to get rawBody?
Answered
Artois Hound posted this in #help-forum
Artois HoundOP
I had a working code setup to get the rawBody from
but now that
my previous solution was
with the bodyParser turned off
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 Horned oak gall
there's also a blog post that does that manually: https://vancelucas.com/blog/how-to-access-raw-body-data-with-next-js/
11 Replies
Horned oak gall
what about
request.text() within the route handler function?@Horned oak gall what about `request.text()` within the route handler function?
Artois HoundOP
Property 'text' does not exist on type 'NextApiRequest'.ts(2339)Horned oak gall
what nextjs version are you using?
Artois HoundOP
14.2.4
Horned oak gall
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();@Horned oak gall 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();
Artois HoundOP
I am using Pages Directory https://nextjs.org/docs/pages/building-your-application/routing/api-routes
and it says
and it says
import type { NextApiRequest, NextApiResponse } from 'next' as export default function handler(
req: NextApiRequest,
res: NextApiResponse<ResponseData>
)Horned oak gall
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
Horned oak gall
there's also a blog post that does that manually: https://vancelucas.com/blog/how-to-access-raw-body-data-with-next-js/
Answer
@Horned oak gall there's also a blog post that does that manually: https://vancelucas.com/blog/how-to-access-raw-body-data-with-next-js/
Artois HoundOP
Nevermind, this works.
I tried it before, but I messed something up, but on a second run it's great.
Thanks m8 @Horned oak gall 🙂