Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: match .json method responses in API routes/Middleware #33592

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 6 additions & 16 deletions packages/next/server/api-utils.ts
Expand Up @@ -89,7 +89,7 @@ export async function apiResolver(
}
apiRes.status = (statusCode) => sendStatusCode(apiRes, statusCode)
apiRes.send = (data) => sendData(apiReq, apiRes, data)
apiRes.json = (data) => sendJson(apiRes, data)
apiRes.json = apiRes.send
apiRes.redirect = (statusOrUrl: number | string, url?: string) =>
redirect(apiRes, statusOrUrl, url)
apiRes.setPreviewData = (data, options = {}) =>
Expand Down Expand Up @@ -266,7 +266,7 @@ export function sendData(
res: NextApiResponse,
body: any
): void {
if (body === null || body === undefined) {
if (body === undefined) {
res.end()
return
}
Expand Down Expand Up @@ -297,7 +297,10 @@ export function sendData(
return
}

const isJSONLike = ['object', 'number', 'boolean'].includes(typeof body)
const isJSONLike = ['object', 'number', 'boolean', 'string'].includes(
typeof body
)

const stringifiedBody = isJSONLike ? JSON.stringify(body) : body
const etag = generateETag(stringifiedBody)
if (sendEtagResponse(req, res, etag)) {
Expand All @@ -321,19 +324,6 @@ export function sendData(
res.end(stringifiedBody)
}

/**
* Send `JSON` object
* @param res response object
* @param jsonBody of data
*/
export function sendJson(res: NextApiResponse, jsonBody: any): void {
// Set header to application/json
res.setHeader('Content-Type', 'application/json; charset=utf-8')

// Use send to handle request
res.send(jsonBody)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of changing the behavior of res.send do we want to just do res.send(JSON.stringify(jsonBody)) here which should match the middleware Response helper here?

static json(body: any) {
return new NextResponse(JSON.stringify(body), {
headers: { 'content-type': 'application/json' },
})
}

}

const COOKIE_NAME_PRERENDER_BYPASS = `__prerender_bypass`
const COOKIE_NAME_PRERENDER_DATA = `__next_preview_data`

Expand Down
3 changes: 3 additions & 0 deletions test/integration/api-support/pages/api/json-null.js
@@ -0,0 +1,3 @@
export default (req, res) => {
res.json(null)
}
3 changes: 3 additions & 0 deletions test/integration/api-support/pages/api/json-string.js
@@ -0,0 +1,3 @@
export default (req, res) => {
res.json('Hello world!')
}
28 changes: 24 additions & 4 deletions test/integration/api-support/test/index.test.js
Expand Up @@ -94,7 +94,7 @@ function runTests(dev = false) {
const text = await fetchViaHTTP(appPort, '/api', null, {}).then(
(res) => res.ok && res.text()
)
expect(text).toEqual('Index should work')
expect(text).toEqual('"Index should work"')
})

it('should return custom error', async () => {
Expand Down Expand Up @@ -162,8 +162,28 @@ function runTests(dev = false) {
expect(body).toBe(true)
})

it('should support string for JSON in api page', async () => {
const res = await fetchViaHTTP(appPort, '/api/json-string')
const body = res.ok ? await res.json() : 'Some error'
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe(
'application/json; charset=utf-8'
)
expect(body).toBe('Hello world!')
})

it('should support null for JSON in api page', 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 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('')
})
Expand Down Expand Up @@ -501,7 +521,7 @@ function runTests(dev = false) {
expect(stderr).toContain(
`API resolved without sending a response for ${apiURL}, this may result in stalled requests.`
)
expect(await req.text()).toBe('hello world')
expect(await req.text()).toBe('"hello world"')
})

it('should not show warning if using externalResolver flag', async () => {
Expand All @@ -511,7 +531,7 @@ function runTests(dev = false) {
expect(stderr.substr(startIdx)).not.toContain(
`API resolved without sending a response for ${apiURL}`
)
expect(await req.text()).toBe('hello world')
expect(await req.text()).toBe('"hello world"')
})
} else {
it('should show warning with next export', async () => {
Expand Down