#How to retrieve values from a request body after JSON.stringify?

1 messages · Page 1 of 1 (latest)

acoustic pond
#

Given the fetch call is:

const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ usernameInput, pwInput }),

And the route file is:

export async function POST(
req: NextApiRequest,
res: NextApiResponse
) {
try {

} catch (error) {
return NextResponse.json(
{
result: {}
},
{
status: 401,
statusText: "Invalid credentials."
}
);
}
}

How do I retrieve the usernameInput and pwInput inside the try-catch?

idle sorrelBOT
#

Hi @acoustic pond. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To retrieve the usernameInput and pwInput from the request body in your Next.js API route, you can use the request.json() method. This method reads the request body and returns it as a JavaScript object. Here's how you can do it:

export async function POST(request: Request) {
  try {
    const { usernameInput, pwInput } = await request.json();

    // Now you can use usernameInput and pwInput
    console.log(usernameInput, pwInput);

  } catch (error) {
    return NextResponse.json(
      { 
          result: {} 
      }, 
      { 
          status: 401,
          statusText: "Invalid credentials."
      }
    );
  }
}

Please note that the request.json() method can only be called once, as the request body becomes locked after it's read. This means you can't consume the request body again after calling request.json()[^1^].

^1^]: [Github Issue (closed): Issue with POST request handling in Next.js API route next 13.4.4 > Comments Part 9 (https://github.com/vercel/next.js/issues/50491)

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: