NEXT API Middleware not able to parse request body returns null

Viewed 305

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?

0 Answers
Related