Next.js Discord

Discord Forum

Have to parse body manually next.js 14

Answered
Alligator mississippiensis posted this in #help-forum
Open in Discord
Alligator mississippiensisOP
Hi guys, I am having problems parsing theb json body, it works if parsed manually but is it possible to parse it automatically?

If I use req.body directly:

The output of req.body is: ReadableStream { locked: false, state: 'readable', supportsBYOB: false }
.
But if I parse it manually it works properly:
import { NextApiRequest, NextApiResponse } from "next";

export default async function handler(
  req: NextApiRequest, res: NextApiResponse
) {
  try {
    const isStream = typeof req.body === 'object' && req.body?.constructor?.name === 'ReadableStream';
    let parsedBody = req.body;

    if (isStream) {
      const chunks = [];
      for await (const chunk of req.body) {
        chunks.push(chunk);
      }

      const rawBody = Buffer.concat(chunks).toString('utf-8');
      parsedBody = JSON.parse(rawBody);
    }

    // Extract stripeId and userId from parsed body
    const { stripeId, userId } = parsedBody;

    if (!stripeId) {
      return res.status(400).json({ error: "stripeId is missing!" });
    }

    if (!userId) {
      return res.status(400).json({ error: "userId is missing!" });
    }

    return res.status(200).json({ 
      stripeId,
      userId,
    });

  } catch (error) {
    console.error("Handler error:", error);
    return res.status(500).json({ error: error.toString() });
  }
}
Answered by Ray
you should do
  const { stripeId, userId } = await req.json()
View full answer

17 Replies

@Ray is it a route handler in a `route.ts` file?
Alligator mississippiensisOP
yes
you should do
  const { stripeId, userId } = await req.json()
Answer
@Ray you should do ts const { stripeId, userId } = await req.json()
Alligator mississippiensisOP
Oh, okay thanks. I was trying req.body.json() first.
Property 'json' does not exist on type 'NextApiRequest'.ts(2339)
the route handler look like this
export async function POST(req: NextRequest) {}
the req type can be Request or NextRequest
Alligator mississippiensisOP
Okay, thank you. I will give it a try.
also use return NextResponse.json() instead or res.status.json()
@Ray also use `return NextResponse.json()` instead or `res.status.json()`
Alligator mississippiensisOP
Yes, thank you very much.
I am currently migrating from blitz.js aka fork of next.js 13.
ah is blitz still being maintained
@Ray ah is blitz still being maintained
Alligator mississippiensisOP
I am not sure, I had to stop using it due to it not supporting next.js 14.
ah ok
Alligator mississippiensisOP
But on github it isnt archived and last release was month ago maybe somehting has changed?
not sure, I haven't checked it for long time 😆