diff --git a/packages/next/server/api-utils/node.ts b/packages/next/server/api-utils/node.ts index 310c0afd12f4246..62e18957f552ba7 100644 --- a/packages/next/server/api-utils/node.ts +++ b/packages/next/server/api-utils/node.ts @@ -442,7 +442,7 @@ function sendJson(res: NextApiResponse, jsonBody: any): void { res.setHeader('Content-Type', 'application/json; charset=utf-8') // Use send to handle request - res.send(jsonBody) + res.send(JSON.stringify(jsonBody)) } function isNotValidData(str: string): boolean { diff --git a/test/integration/api-support/pages/api/json-null.js b/test/integration/api-support/pages/api/json-null.js new file mode 100644 index 000000000000000..b0bac6f5f9fad52 --- /dev/null +++ b/test/integration/api-support/pages/api/json-null.js @@ -0,0 +1,3 @@ +export default (req, res) => { + res.json(null) +} diff --git a/test/integration/api-support/pages/api/json-string.js b/test/integration/api-support/pages/api/json-string.js new file mode 100644 index 000000000000000..f8eb8f057157354 --- /dev/null +++ b/test/integration/api-support/pages/api/json-string.js @@ -0,0 +1,3 @@ +export default (req, res) => { + res.json('Hello world!') +} diff --git a/test/integration/api-support/pages/api/undefined.js b/test/integration/api-support/pages/api/json-undefined.js similarity index 100% rename from test/integration/api-support/pages/api/undefined.js rename to test/integration/api-support/pages/api/json-undefined.js diff --git a/test/integration/api-support/test/index.test.js b/test/integration/api-support/test/index.test.js index 09df1e904625626..12b22adcc99a06a 100644 --- a/test/integration/api-support/test/index.test.js +++ b/test/integration/api-support/test/index.test.js @@ -163,11 +163,27 @@ function runTests(dev = false) { }) it('should support undefined response body', async () => { - const res = await fetchViaHTTP(appPort, '/api/undefined', null, {}) + const res = await fetchViaHTTP(appPort, '/api/json-undefined', null, {}) const body = res.ok ? await res.text() : null expect(body).toBe('') }) + it('should support string in JSON response body', async () => { + const res = await fetchViaHTTP(appPort, '/api/json-string', null, {}) + const body = res.ok ? await res.text() : null + expect(body).toBe('"Hello world!"') + }) + + it('should support null in JSON response body', async () => { + const res = await fetchViaHTTP(appPort, '/api/json-null') + const body = res.ok ? await res.json() : 'Not null' + expect(res.status).toBe(200) + expect(res.headers.get('content-type')).toBe( + 'application/json; charset=utf-8' + ) + expect(body).toBe(null) + }) + it('should return error with invalid JSON', async () => { const data = await fetchViaHTTP(appPort, '/api/parse', null, { method: 'POST',