NextJS API Route does not recognize or parse JSON

89 Views Asked by At

I'm experimenting with nextjs+react and can't figure out something extremely trivial - sending and receiving a post request via the internal API: The stringified JSON is not recognized and thus not parsed correctly.

Client component

const data1 = { key: 'test123' };

const response = await fetch('/api/chat', {
   method: 'POST',
   headers: {
      'content-type': 'application/json'
       },
   body: JSON.stringify(data1),
      });

API page (/pages/api/chat.tsx)

export default async function handler(req: NextApiRequest,
    res: NextApiResponse): Promise<any> {

    const data = JSON.parse(req.body)
    console.log(data)
}

Error
The console prints the error:

pages/api/chat.tsx (10:22) @ parse ⨯ SyntaxError: "[object Object]" is not valid JSON
at JSON.parse (<anonymous>)
at handler (webpack-internal:///(api)/./pages/api/chat.tsx:6:23)

From what I've read, nextjs should understand the body as json because it is set in the headers of the request. However, this does not work.

Where am I wrong?

1

There are 1 best solutions below

0
Jason R Stevens CFA On

Next.js automatically parses the Content-Type of the body parameter. See the docs here.

In your case, simply remove the usage of JSON.parse in your api route, e.g.:

export default async function handler(req: NextApiRequest,
    res: NextApiResponse): Promise<any> {

    const data = req.body
    console.log(data)
}