question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Middleware in API have a null body on POST Requests

See original GitHub issue

What version of Next.js are you using?

12.0.2

What version of Node.js are you using?

v14.18.0

What browser are you using?

Chrome

What operating system are you using?

Linux

How are you deploying your application?

next dev, next start, Vercel

Describe the Bug

When sending a POST request that gets handled by middleware in the /pages/api folder, the request body is always null.

So, in the client side (/pages/index.tsx) we have:

    fetch("/api/middlewaretest", {
      method: "post",
      body: JSON.stringify({ hello: "world" }),
      headers: { "content-type": "application/json" },
    })
      .then((res) => res.json())
      .then((res) => console.log(res))
      .catch((e) => {
        console.error(e);
      });
  };

In /api/middlewaretest/_middleware.ts we have:


export function middleware(req: NextRequest, ev: NextFetchEvent) {
  console.log("method", req.method); // will be post
  console.log("bodyUsed", req.bodyUsed); // will be false
  console.log("headers", req.headers); // shows proper content type and content length
  console.log("body", req.body); // always null!

  /***
   *
   * If middleware is async and I try any of the following:
   *
   * await res.json() // TypeError: invalid json body reason: Unexpected end of JSON input
   * await res.text() // blank string
   *
   */
  return new Response(JSON.stringify({ message: "hello world!" }), {
    status: 200,
    headers: {
      "Content-Type": "application/json",
    },
  });
}

Expected Behavior

In https://nextjs.org/docs/api-reference/next/server#nextrequest it notes that NextRequest is an extension of the native Request interface which should provide a stream on req.body that could be read. However, it always comes across as null.

To Reproduce

  1. Clone https://github.com/idreaminteractive/nextjs-middleware-body
  2. yarn
  3. yarn dev (or yarn build && yarn start)
  4. Goto http://localhost:3000
  5. Press the Send the post button to trigger the middleware, check the console logs to see req.body is always null for a POST request.

The second button (Send the post to hello) is a regular NextJS API end point and works fine.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:7
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
Schnizcommented, Feb 10, 2022

I will tackle this ✋

3reactions
jessehalperncommented, Jan 15, 2022

Are these sorts of limitations documented anywhere? As excited as I am about middleware, it can be time consuming to diagnose whether we’ve done something wrong in our setup, or if it just isn’t possible today

This part of the documentation even strongly implies that this is possible: https://nextjs.org/docs/api-reference/next/server#why-does-redirect-use-307-and-308

Read more comments on GitHub >

github_iconTop Results From Across the Web

req.body is NULL {} on POST request - Stack Overflow
On post request from POSTMAN req.body is sending the data but returns { } when submitting the form. This is what I used...
Read more >
RestRserve.pdf
Middleware is a very useful concept which allows to perform preprocessing of requests and post- processing of responses. Middleware has an ...
Read more >
Missing req.body · Issue #202 · chimurai/http-proxy-middleware
This example uses the "body-parser" module in the main app to create a req. body object with the decoded POST parameters. Side note...
Read more >
How we built a Node.js Middleware to Log HTTP API ... - Moesif
Logging the BodyPermalink ... The request body is still not logged, which means POST, PUT and PATCH requests aren't 100% covered. To get...
Read more >
Handling errors in ASP.NET Core Web API - DevTrends
The problem is that when exception happens inside of a post action, request body will become null. It happens because request body has...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found