Bigboss01
Bigboss01

Reputation: 628

Decode ReadableStream object nextjs 13 api route

I'm sending a value to my server side code that isn't being read correctly. I'm using the NextJS experimental App directory

//src/app/api/auth/route.js

export async function POST(req, res) {
  console.log(req.body);
  const { address } = req.body;
  const isAuthenticated = await checkBalance(address, threshold);
  if (isAuthenticated) {
    return new Response("Authorized", { status: 200 });
  } else if (isAuthenticated == false) {
    return new Response("Unauthorized", { status: 401 });
  } else if (isAuthenticated == undefined) {
    return new Response("Error", { status: 500 });
  }
}

console log is: ReadableStream { locked: false, state: 'readable', supportsBYOB: false }

const address is undefined.

This is the api call:

const response = await fetch("/api/auth", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ address: walletAddress }),
        });
        const data = await response.json();

I read in another answer to a similar question that nextjs12+ is supposed to parse the request automatically- what am I doing wrong? I'm assuming that nextjs has a protocol in place for decoding the ReadableStream but I can't find anything in the docs or examples for this, maybe because there is a framework agnostic method for decoding the object that is unknown to me?

Thank you in advance.

Upvotes: 8

Views: 17856

Answers (4)

Mahmod Issa
Mahmod Issa

Reputation: 81

you need to await the request from nextjs in order to get the body object. Like the code bellow:

import { NextResponse } from "next/server";

export async function POST(req) {
    
    const body = await req.json();
    console.log(body);
    
    return NextResponse.json(body);
}

Upvotes: 8

FahadAlAraik
FahadAlAraik

Reputation: 326

I've faced a similiar problem, you can try this:

const body = await req.json()
const {address} = body
// the rest of your code 

Upvotes: 31

Bigboss01
Bigboss01

Reputation: 628

A discord user recommended const address = await req.json(); instead of const {address} = req.body and it works.

Upvotes: 1

Ogrodev
Ogrodev

Reputation: 326

I think what you want to do is:

...
const { address } = req.body
const isAuthenticated = await checkBalance(address, threshold);
...

Upvotes: 0

Related Questions