Next.js Discord

Discord Forum

Post Request pending forever

Answered
MyOwnBrain posted this in #help-forum
Open in Discord
I am trying to send a Post request from the Client to the Next.js server. But somehow await req.text() es loading forever and I don't know why. The structure is much more complex, but to evaluate the Problem I made a test route to check what causes the problem. The Test route looks like this:
import {NextRequest, NextResponse} from 'next/server';

export async function POST(req: NextRequest) {
    await req.text();

    return NextResponse.json({test: 'dummy'});
}


And this is how I send the request (Submit function of a Button click):
const handleSubmit = async () => {
    await axios.post('/api/backend/product/post', {test: 'test'}, {
        headers: {
            'Content-Type': 'application/json',
        },
    });
};


When commenting await req.text() out it immediately responds. I also tried using fetch instead of axios, but that didn't work ether. The api path is also excluded from the middleware.
What am I doing wrong? If you need further information just ask.
Answered by MyOwnBrain
I found a solution. I reset the whole Windows 11 Firewall, but that might not be required. After restarting my PC I run bun --bun dev in my test app (as I always do). I got the prompt for Network/Firewall rules and just clicked accept. With that the problem still was preset. I thought maybe I need to run it with npm so it can recreate the Firewall rules for node, since bun is build for max node compatibility. With npm run dev I got the Network/Firewall rules prompt again, but for the program in program files and also just clicked accept. I tested again (with the dev server still running using npm run dev) and the problem was gone. Then I tested with bun dev and the problem was gone here as well. The --bun flag forces executing with the bun runtime instead of using node. So my conclusion is, that the problem comes from the bun runtime. With that resetting the Firewall is not necessary I think.
Next.js version 15.2.4
Bun version 1.2.7
View full answer

98 Replies

No, this does not work with Route Handlers.
@MyOwnBrain No, this does not work with Route Handlers.
Dutch
but you are using them now
No I mean res does not work. I use req
@MyOwnBrain No I mean `res` does not work. I use `req`
Dutch
it should work
every request has res req
In the docs there is only req. There is a difference between POST and handler
Dutch
use server actions
if not remove that await and continue
Ok I will try server actions, but what is the point of removing await. Without it I just get nothing back.
But I need it.
Dutch
why
The original Route uses the Data to fetch our Python API.
Dutch
this is one of my function and there is no req. thing
async function checkToken() {
    if (!token.access_token) console.error("No token found !");
    try {
      const response = await fetch(`${process.env.WEB_API_URL as string}User/TokenCheck/${sessionId}`);
      const result = await response.json();
      return result.result;
    } catch (error) {
      console.error(error);
    }
  }
you need response not request
Yes but mine is a Route Handler. I send an HTTP req from the Client to the Next.js Server. In that request is data in the body, That I need on the server. And I want to read the data from the body.
What you send me is when the response was successful, but my problem is, that the server does not send any response, because it does not finish processing the data send in the request.
The code is in the origional post. It exactly contains the problem. I just did remove the stuff, that is not part of the problem. But I can make the example more specific.
This is the route.ts on the Next.js Server:
import axios from 'axios';
import {NextRequest, NextResponse} from 'next/server';

export async function POST(req: NextRequest) {
    try {
        const json = await req.json();

        const response = await axios.post(`${process.env.BACKEND_HOST}/sheet/product/`, json, {
            headers: {
                Authorization: `Bearer ${req.headers.get('Authorization')}`,
                'Content-Type': 'application/json',
            },
            timeout: 5000,
        });

        if (response.status !== 200) {
            return NextResponse.json({error: response.statusText}, {status: response.status});
        }

        return NextResponse.json(response.data);
    } catch (error: unknown) {
        let status = 500;
        let message = 'An unknown error occurred';

        if (axios.isAxiosError(error)) {
            status = error.response?.status || 500;
            message = error.response?.data || error.message;
        } else if (error instanceof Error) {
            message = error.message;
        }

        return NextResponse.json({error: message}, {status});
    }
}


This is the request, that the Client sends to the Next.js Server:
await axios.post(
    '/api/backend/product/post',
    {test: 'dummy'},
    {
        headers: {
            Authorization: `${accessToken}`,
            'Content-Type': 'application/json',
        },
    }
);


And the line causing the infinite pending is this one on the Server in the route.ts:
const json = await req.json();`
Yes I need it.
Dutch
you are not using it anywhere
I am using it two lines below that
Dutch
this causes infinite loop
you are sending request in that request you send
Yes but to different endpoints.
Dutch
you need to make 2 different requests
you ll send response of POST to axios
I do the same with my get requests and everything works fine. The requests are just chained.
Dutch
is it giving error at req when you write it right ?
oh wait you need req.body
not req.json
req.body is a readable stream. But I need a JSON.
Dutch
it was an issue i am reading it now
one suggestion was try to do, req.text(), instead from next
I already tried req.text(). As written in my original post, the is also present with req.text(). It returns an promise and awaiting it also loads to infinity.
Dutch
is it working with postman
i mean do you see request object when you make it
When trying it with Postman it also loads forever
Dutch
maybe your api is problem then
can you show me an ss of it
What is an ss?
Dutch
screenshot
Which API do you mean?
the Python API?
Dutch
the api loads infinite
request*
make that request and take a screenshot of postman ui
Postman also loads infinite. As I said the problem is, that await req.text() or await req.json() does not resolve. Everything else works fine. It just hangs at that point. This is why I had nothing else in my original example.
Dutch
i want to see that infinite load with my eyes
Dutch
also still suggesting upgrading to newest version
Everything is up to date
Dutch
yes now i got it. I need that /api/backend/product/post endpoint code
if its python still show please
@MyOwnBrain Everything is up to date
Dutch
next versions and using server actions
Dutch
no that endpoint which responds to that request
which gives a response
You mean the one called from the POST function?
Dutch
which has infinite loop
There is no infinit loop. await req.text() just does not resolve.
Dutch
/api/backend/product/post endpoint code
@MyOwnBrain .
Dutch
not this
But there is no other code
Dutch
that endpoint which gives response from that link
/api/backend/product/post
the place you setup its response
the backend
like @app.route(/product/post)
You mean the on called by axios.post() in the try catch block?
Dutch
yep
the place responds to that request
@Dutch the place responds to that request
Don't have access to this one. It runs on a different external server. But as I said it does not cause the loading problem. The POST does not event execute axios.post() to that endpoint, since it stops at await req.text().
Dutch
can you share it via live share on vscode
will debug it on my pc
@MyOwnBrain I am on next version `15.2.4`
hmm your code works fine on my end though
the response is returned immediately as expected
Wait what?
it returns the data as expected
Ok I will try it myself with a clean project.
if it doesn't work with a clean project i can only guess it's some weird firewalls or network settings on your computer
On my machine also a new project also has the same problem. But on another machine it works. I'll try your suggestions and find out what is causing the problem. Sorry for making that much trouble.
Dutch
first time i see this kind of machine issue tbh, hope you can solve it soon
I found a solution. I reset the whole Windows 11 Firewall, but that might not be required. After restarting my PC I run bun --bun dev in my test app (as I always do). I got the prompt for Network/Firewall rules and just clicked accept. With that the problem still was preset. I thought maybe I need to run it with npm so it can recreate the Firewall rules for node, since bun is build for max node compatibility. With npm run dev I got the Network/Firewall rules prompt again, but for the program in program files and also just clicked accept. I tested again (with the dev server still running using npm run dev) and the problem was gone. Then I tested with bun dev and the problem was gone here as well. The --bun flag forces executing with the bun runtime instead of using node. So my conclusion is, that the problem comes from the bun runtime. With that resetting the Firewall is not necessary I think.
Next.js version 15.2.4
Bun version 1.2.7
Answer
@joulev Thank you. You made evaluating the Problem possible for me. Without your confirmation I would never have found the issue.
Glad you figured it out!
I have to correct myself. On my other machine it works with the --bun flag. So it is still a problem of my main PC, but using just bun dev without the --bun flag does fix the problem of my main PC. So the bun runtime is not the problem on its own. Only on my PC it is that weird.
They are both on Windows 11 and bun 1.2.7. I will report this to bun.