Unravel the ReadableStream object in nextjs 13 api route

I am encountering an issue with my server-side code where a value I am sending is not being interpreted correctly. My project is utilizing the experimental App directory feature of NextJS.

//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 });
  }
}

The output from the console log is:

ReadableStream { locked: false, state: 'readable', supportsBYOB: false }

The value of const address is undefined.

This is the API call being made:

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

I came across another answer to a similar problem which mentioned that NextJS version 12 and above should automatically parse the request. Can anyone point out what might be going wrong in my implementation? Is there a specific protocol in place within NextJS for decoding ReadableStreams that I may have missed in the documentation or examples? Perhaps there is a framework-agnostic approach for decoding objects that I am unaware of?

Thank you for any assistance provided.

Answer №1

Dealing with a similar issue, one solution could be:

const requestBody = await req.json()
const {location} = requestBody
// continue coding here 

Answer №2

In order to retrieve the body object from Next.js, it is necessary to use the await keyword to wait for the request. You can achieve this by following the code snippet below:

import { NextResponse } from "next/server";

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

Answer №3

From my perspective, the best course of action would be:

...
const { location } = req.body
const isLoggedIn = await verifyAmount(location, limit);
...

Answer №4

Upon suggestion from a fellow discord member, I tried using

const address = await req.json();
instead of the conventional const {address} = req.body, and surprisingly it turned out to be quite effective.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What exactly does a 'hoisted manifest' mean when it comes to using Yarn?

Encountering an issue while attempting to install a package using yarn, I am receiving the error message: expected hoisted manifest for \"myPackage#@material-ui/core#react-dom\" However, the concept of a 'hoisted manifest' is not entir ...

Some mobile devices are experiencing issues with Android webview not executing javascript functions

Everything was running smoothly on my webview app on the HUAWEI RNE-L22 and iPhone. However, when I tried to run the app on the samsung SM-G530H, it failed to execute my JavaScript function. Surprisingly, the function worked fine on a normal phone browser. ...

A continuous jQuery method for updating select option values

I'm currently working on a form and using jQuery to make some alterations. The form consists of multiple select elements, and I want to change the value of the first option in each of them. However, as the form allows for dynamic addition of new selec ...

My websocket server establishes successful connections with Postman, however, it seems to encounter difficulties when connecting with my React project

After setting up a WebSocket server using Python deployed in an EC2 container, I encountered an issue where connecting through Postman was successful, but attempting to connect via Websocket in React resulted in the following error message: WebSocket conn ...

Adjusting the URL variable based on the selected checkbox option

My mobile website offers users the option of a bright or dark interface using a checkbox styled like an iPhone IOS7 switch. The functionality is working as expected, but I'm now facing an issue with passing the status of the checkbox between pages. I ...

Is it possible for the ".filter" function to verify if the target contains multiple attributes?

I'm currently working on a checkbox filter setup and using Jquery's .filter to sort through some divs. Below is the snippet of Jquery code that I am using: $(document).ready(function(){ var checkboxes = $('div.filter-groups').find(&ap ...

Encountering Difficulty Accessing Index.ejs with Express.js

Currently, I am enrolled in a Linkedin course that focuses on building websites using express.js. I have encountered an issue where my index.ejs page is not rendering properly, as the server keeps loading my index.html page instead. I have tried searching ...

What is the best way to substitute multiple substrings with strings from multiple interconnected arrays?

Looking for a way to manipulate a lengthy string in JS? Seeking to add new characters to each match within the string to create a fresh output? Need to handle multiple occurrences of a specific substring in the long text? Any strategies or suggestions? con ...

Make the navigation bar stay at the top of the page when scrolling past another element with a top position of 100vh

Trying to explain a unique concept here. I want a nav bar fixed in the position of top:100vh, so that as I scroll down and reach the next section, the navbar sticks at the top rather than staying stuck at the beginning with position:fixed top:0. The aim is ...

Having trouble activating the submit function using an external JavaScript file

Having trouble getting the form to submit properly. I have placed the form inside a <div id="access"></div> by setting its innerHTML using an included js file in the header of the page. Here's how it looks: <div id="access"> < ...

Best practices for declaring variables in ReactJS

I need help understanding how to declare a variable in a React JS class so that it is accessible in different functions. Here is my code snippet: class MyContainer extends Component { constructor(props) { super(props); this.testVariable ...

Iterating over an object using ng-repeat in Angular, where the value is an array

In my data object, I have key-value pairs where the value is an array. Each array contains objects with various properties. $scope.testObj = { "London":[ {"id":1,"city":"London","country":"GB","name":"Test1"}, {"id":4,"city":"London" ...

I am attempting to get a jquery plugin to function properly on my Windows 7 Internet Explorer IE7 browser. The plugin in question can be found at http://jvectormap.owl-hollow

I'm encountering some strange issues with my Internet Explorer IE7 browser on Windows 7. The jquery plugin I am attempting to use can be found at . Unfortunately, this plugin is not functioning properly on Internet Explorer IE7 on Windows 7, but it ru ...

Experiencing network request failure on one specific URL while using React Native for iOS, but having no issues with other URLs

I'm facing an issue in my React Native app while trying to make an API call using the following code: test = async () => { try { let a = await fetch('https://rxapitest.alliancepharmacygroup.ca:12345/', { method: 'G ...

Tips on choosing one specific JSON object from a group and exploring its structure in Python

Looking for guidance to access a specific javascript element named SOURCE.pdp.propertyJSON and extract its attributes in a Pythonic way from a webpage filled with different script elements. Browse through the HTML source code below to get an idea and then ...

Styling Javascript Objects

[ [ {"path":"path2","value":"kkk"}, {"path":"path0","value":"uuu"}, {"path":"path1","value":"ppp"} ] ] The result obtained from my manipulation is shown above. However, I require the format to be as depicted below: ["path":"pat ...

What is the mechanism for invoking functions defined with the arrow syntax in Angular?

Referencing this code snippet from the tutorial at https://angular.io/tutorial/toh-pt4, specifically within the hero.component.ts file: getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } After analyz ...

What could be causing Ember/handlebars.js to prepend 'app/' to my template file names?

Whenever I try to load my Rails ember app, I encounter a frustrating issue where Ember is unable to locate the application and index templates. Ember.TEMPLATES['application] and Ember.TEMPLATES['index'] Oddly enough, when I check Ember.TEM ...

Can you explain the concept of "pre-rendering a page before a user makes a request"?

Currently, I'm diving into Next.js and exploring the distinction between static generation and server-side rendering (SSR). While reading through their documentation, one sentence caught my attention: "On the other hand, Static Generation is not a goo ...

"Webpack error: Including a comma within a string leads to a syntax problem when bund

I'm attempting to merge this file into my main JS. var constants = { height: 600, width: 400, default_bezier = "[ { \"startPoint\" : [51.6503017608354,203.464445873753], \"endPoint\" : [-52.41285540263849,202.372456432 ...