#Have to parse body manually next.js 14

19 messages · Page 1 of 1 (latest)

harsh nest
#

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() });
  }
}
neon mantleBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

vocal estuary
vocal estuary
#

you should do

  const { stripeId, userId } = await req.json()
harsh nest
#

Property 'json' does not exist on type 'NextApiRequest'.ts(2339)

vocal estuary
#

the route handler look like this

export async function POST(req: NextRequest) {}
#

the req type can be Request or NextRequest

harsh nest
#

Okay, thank you. I will give it a try.

vocal estuary
#

also use return NextResponse.json() instead or res.status.json()

harsh nest
#

I am currently migrating from blitz.js aka fork of next.js 13.

vocal estuary
#

ah is blitz still being maintained

harsh nest
vocal estuary
#

ah ok

harsh nest
#

But on github it isnt archived and last release was month ago maybe somehting has changed?

vocal estuary
#

not sure, I haven't checked it for long time 😆