diff --git a/packages/next/next-server/server/api-utils.ts b/packages/next/next-server/server/api-utils.ts index 2de7ab56cd5b4..c2fc5c61e46a6 100644 --- a/packages/next/next-server/server/api-utils.ts +++ b/packages/next/next-server/server/api-utils.ts @@ -104,6 +104,11 @@ export async function parseBody(req: NextApiRequest, limit: string | number) { * @param str `JSON` string */ function parseJson(str: string) { + if (str.length === 0) { + // special-case empty json body, as it's a common client-side mistake + return {} + } + try { return JSON.parse(str) } catch (e) { diff --git a/test/integration/api-support/test/index.test.js b/test/integration/api-support/test/index.test.js index 1f09a0bece55f..954260192f04c 100644 --- a/test/integration/api-support/test/index.test.js +++ b/test/integration/api-support/test/index.test.js @@ -75,6 +75,17 @@ function runTests(dev = false) { expect(data).toEqual([{ title: 'Nextjs' }]) }) + it('should special-case empty JSON body', async () => { + const data = await fetchViaHTTP(appPort, '/api/parse', null, { + method: 'POST', + headers: { + 'Content-Type': 'application/json; charset=utf-8', + }, + }).then(res => res.ok && res.json()) + + expect(data).toEqual({}) + }) + it('should return error with invalid JSON', async () => { const data = await fetchViaHTTP(appPort, '/api/parse', null, { method: 'POST',