Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access request body in nextjs 13.2 route handler

I was trying to send a post request to my api. However trying to access the request body in the route handler causes the error below:

Code:

export async function POST(request: Request) {
  const postBody: postProps = JSON.parse(request.body) // 👈 Error here on request.body
  ...
}

Error: Argument of type 'ReadableStream' is not assignable to parameter of type 'string'.

Any help would be appreciated

like image 286
lool Avatar asked Sep 05 '25 03:09

lool


2 Answers

You need to call json() on the Request object.

export async function POST(request: Request) {
  const res = await request.json() // res now contains body
}
like image 107
Michael Avatar answered Sep 07 '25 20:09

Michael


I was having issues Verifying the webhook from Clerk in Next.js using App Router.

The following worked for me.

import { Webhook } from "svix";

export async function POST(req: NextRequest) {
  const svix_id = req.headers.get("svix-id") ?? '';
  const svix_timestamp = req.headers.get("svix-timestamp") ?? '';
  const svix_signature = req.headers.get("svix-signature") ?? '';
  
  const body = await req.text(); // This get's the raw body as a string
  
  const sivx =  new Webhook("your_secret_key_here")

  const payload = sivx.verify(body, {
    "svix-id": svix_id,
    "svix-timestamp": svix_timestamp,
    "svix-signature": svix_signature,

  });

  // The payload is the json.
  console.log(payload);

  // The rest of your code

  return NextResponse.json(null, { status: 200 })

}


For reference:

https://developer.mozilla.org/en-US/docs/Web/API/Response/text

like image 43
Kyle Davis Avatar answered Sep 07 '25 20:09

Kyle Davis