Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js Route API - Getting Body Values

I am trying out the new Route API's in Next v13.2, but cannot seem to figure out how to get the body values in a POST request.

On the client side, I am calling the API something like this:

      const response = await fetch("/api/bot", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ prompt: "Testing" }),
      });

I then created a file in the app directory called route.js

I created the function for the POST request and tried fetching the values from the request object in numerous ways, with no luck.

Something like:

export async function POST(request) {
  console.log("Request", request.body.prompt);
  return new Response({ response: prompt });
}

I tried fetching the body values from the request objects, but nothing seems to work.

like image 266
Leon van Zyl Avatar asked Apr 25 '26 20:04

Leon van Zyl


1 Answers

With Next.js 13.4 by sending the POST request like this:

const response = await fetch("/api/bot", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ prompt: "Testing" }),
      });

you can make the following to extract the body data:

import { NextResponse } from 'next/server'

export async function POST(req) {
  const body = await req.json()
  return NextResponse.json({prompt: body.prompt})
}
like image 71
Ram Farid Avatar answered Apr 27 '26 08:04

Ram Farid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!