diff --git a/packages/next/next-server/server/api-utils.ts b/packages/next/next-server/server/api-utils.ts index f04176eb33d9..07f34d68b66b 100644 --- a/packages/next/next-server/server/api-utils.ts +++ b/packages/next/next-server/server/api-utils.ts @@ -229,7 +229,7 @@ export function sendData( res: NextApiResponse, body: any ): void { - if (body === null) { + if (body === null || body === undefined) { res.end() return } diff --git a/test/integration/api-support/pages/api/undefined.js b/test/integration/api-support/pages/api/undefined.js new file mode 100644 index 000000000000..0ccd4fcc75e9 --- /dev/null +++ b/test/integration/api-support/pages/api/undefined.js @@ -0,0 +1,3 @@ +export default (req, res) => { + res.json(undefined) +} diff --git a/test/integration/api-support/test/index.test.js b/test/integration/api-support/test/index.test.js index a7fec5424ccf..de878765f842 100644 --- a/test/integration/api-support/test/index.test.js +++ b/test/integration/api-support/test/index.test.js @@ -122,6 +122,12 @@ function runTests(dev = false) { expect(body).toBe(true) }) + it('should support undefined response body', async () => { + const res = await fetchViaHTTP(appPort, '/api/undefined', null, {}) + const body = res.ok ? await res.text() : null + expect(body).toBe('') + }) + it('should return error with invalid JSON', async () => { const data = await fetchViaHTTP(appPort, '/api/parse', null, { method: 'POST',