Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NEXT API Middleware not able to parse request body returns null

Tags:

next.js

I have created a middleware as pages/api/open/_middleware.ts. Here's the code:

import { NextResponse } from 'next/server';
import { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  // create an instance of the class to access the public methods. This uses `next()`,
  // you could use `redirect()` or `rewrite()` as well
  console.log(
    request.method,
    request.body,
    request.headers.get('Authorization')
  );

  let response = NextResponse.next();
  // get the cookies from the request
  if (request.method === 'GET')
    return NextResponse.json({ name: 'UnAuthenticated' });
  return response;
}

I tried to make request from VSCode Http Client, Postman and Python too. But in all cases the request.body is consoled as null:

VSCode Client:

POST http://localhost:3000/api/open HTTP/1.1
Content-Type: application/json
Authorization: xxxxxxxxxxxxxxxxx
Accept: application/json

{
  "name": "My First Project",
  "description": "This is my first project",
  "url": "http://localhost:3000/api/open"
}

Postman Client: enter image description here

Python Requests module:

>>> from requests import post
>>> post("http://localhost:3000/api/open",json={"a":1})
<Response [200]>
>>> headers={"Content-Type":"application/json"}
>>> post("http://localhost:3000/api/open",json={"a":1},headers=headers)
<Response [200]>
>>> 

But all of this print null in console:

event - compiled successfully in 60 ms (151 modules)
POST null xxxxxxxxxxxxxxxxx

Headers are parsed correctly but the body never gets parsed even after specifying content-type.

Can someone help me understand what's going wrong here? Aren't middleware supposed to intercept the request body?

like image 595
Shivam Sahil Avatar asked Mar 04 '26 18:03

Shivam Sahil


1 Answers

I think the request object is an extension of the Fetch API Request interface. To read the body you can use the json method directly on the request object, which returns a promise which "resolves with the result of parsing the body text as JSON": await request.json()

see https://developer.mozilla.org/en-US/docs/Web/API/Request/json

Seeing that you are reading the body in middleware, you may want to consider using the .clone() method so you don't remove the body from the original request object.

like image 175
spflow Avatar answered Mar 07 '26 17:03

spflow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!