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

Conversation

balazsorban44
Copy link
Member

Fixes #21749

pages/middleware/_middleware.js:

import { NextResponse } from "next/server"

export default function middleware() {
  return NextResponse.json("string")
  // return NextResponse.json(null)
}

pages/api/index.js:

export default function handler(req, res) {
  res.json("string")
  // res.json(null)
}

Output from a JSON prettifier Chrome extension (but tested with curl http://localhost:3000/{api,middleware} also):

image

image

In https://nextjs.org/docs/api-routes/response-helpers

We document this method as:

must be a serializable object

and both JSON.stringify(null) and JSON.stringify("string") works.

Bug

  • Related issues linked using fixes #number
  • Integration tests added
  • Errors have helpful link attached, see contributing.md

Feature

  • Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
  • Related issues linked using fixes #number
  • Integration tests added
  • Documentation added
  • Telemetry added. In case of a feature if it's used or not.
  • Errors have helpful link attached, see contributing.md

Documentation / Examples

  • Make sure the linting passes by running yarn lint

@ijjk
Copy link
Member

ijjk commented Jan 24, 2022

Failing test suites

Commit: ef76227

test/integration/bigint/test/index.test.js

  • bigint API route support > dev mode > should return the BigInt result text
  • bigint API route support > server mode > should return the BigInt result text
  • bigint API route support > serverless mode > should return the BigInt result text
Expand output

● bigint API route support › dev mode › should return the BigInt result text

expect(received).toEqual(expected) // deep equality

Expected: "3"
Received: "\"3\""

  24 |     expect(res.status).toEqual(200)
  25 |   })
> 26 |
     | ^
  27 |   it('should return the BigInt result text', async () => {
  28 |     const resText = await fetchViaHTTP(appPort, '/api/bigint', null, {
  29 |       method: 'GET',

  at Object.<anonymous> (integration/bigint/test/index.test.js:26:25)

● bigint API route support › server mode › should return the BigInt result text

expect(received).toEqual(expected) // deep equality

Expected: "3"
Received: "\"3\""

  24 |     expect(res.status).toEqual(200)
  25 |   })
> 26 |
     | ^
  27 |   it('should return the BigInt result text', async () => {
  28 |     const resText = await fetchViaHTTP(appPort, '/api/bigint', null, {
  29 |       method: 'GET',

  at Object.<anonymous> (integration/bigint/test/index.test.js:26:25)

● bigint API route support › serverless mode › should return the BigInt result text

expect(received).toEqual(expected) // deep equality

Expected: "3"
Received: "\"3\""

  24 |     expect(res.status).toEqual(200)
  25 |   })
> 26 |
     | ^
  27 |   it('should return the BigInt result text', async () => {
  28 |     const resText = await fetchViaHTTP(appPort, '/api/bigint', null, {
  29 |       method: 'GET',

  at Object.<anonymous> (integration/bigint/test/index.test.js:26:25)

@ijjk
Copy link
Member

ijjk commented Jan 24, 2022

Stats from current PR

Default Build (Increase detected ⚠️)
General Overall decrease ✓
vercel/next.js canary vercel/next.js fix/match-json-method-responses Change
buildDuration 14.8s 14.8s -40ms
buildDurationCached 3.8s 4s ⚠️ +172ms
nodeModulesSize 355 MB 355 MB -657 B
Page Load Tests Overall increase ✓
vercel/next.js canary vercel/next.js fix/match-json-method-responses Change
/ failed reqs 0 0
/ total time (seconds) 3.485 3.503 ⚠️ +0.02
/ avg req/sec 717.46 713.71 ⚠️ -3.75
/error-in-render failed reqs 0 0
/error-in-render total time (seconds) 1.657 1.609 -0.05
/error-in-render avg req/sec 1508.53 1553.83 +45.3
Client Bundles (main, webpack, commons)
vercel/next.js canary vercel/next.js fix/match-json-method-responses Change
450.HASH.js gzip 179 B 179 B
framework-HASH.js gzip 42.2 kB 42.2 kB
main-HASH.js gzip 27.2 kB 27.2 kB
webpack-HASH.js gzip 1.44 kB 1.44 kB
Overall change 71 kB 71 kB
Legacy Client Bundles (polyfills)
vercel/next.js canary vercel/next.js fix/match-json-method-responses Change
polyfills-HASH.js gzip 31 kB 31 kB
Overall change 31 kB 31 kB
Client Pages
vercel/next.js canary vercel/next.js fix/match-json-method-responses Change
_app-HASH.js gzip 1.37 kB 1.37 kB
_error-HASH.js gzip 194 B 194 B
amp-HASH.js gzip 312 B 312 B
css-HASH.js gzip 326 B 326 B
dynamic-HASH.js gzip 2.37 kB 2.37 kB
head-HASH.js gzip 350 B 350 B
hooks-HASH.js gzip 919 B 919 B
image-HASH.js gzip 4.87 kB 4.87 kB
index-HASH.js gzip 263 B 263 B
link-HASH.js gzip 2.13 kB 2.13 kB
routerDirect..HASH.js gzip 321 B 321 B
script-HASH.js gzip 383 B 383 B
withRouter-HASH.js gzip 318 B 318 B
85e02e95b279..7e3.css gzip 107 B 107 B
Overall change 14.2 kB 14.2 kB
Client Build Manifests
vercel/next.js canary vercel/next.js fix/match-json-method-responses Change
_buildManifest.js gzip 459 B 459 B
Overall change 459 B 459 B
Rendered Page Sizes
vercel/next.js canary vercel/next.js fix/match-json-method-responses Change
index.html gzip 530 B 530 B
link.html gzip 544 B 544 B
withRouter.html gzip 525 B 525 B
Overall change 1.6 kB 1.6 kB

Default Build with SWC (Increase detected ⚠️)
General Overall decrease ✓
vercel/next.js canary vercel/next.js fix/match-json-method-responses Change
buildDuration 18.4s 18.5s ⚠️ +95ms
buildDurationCached 4s 3.8s -223ms
nodeModulesSize 355 MB 355 MB -657 B
Page Load Tests Overall increase ✓
vercel/next.js canary vercel/next.js fix/match-json-method-responses Change
/ failed reqs 0 0
/ total time (seconds) 3.476 3.502 ⚠️ +0.03
/ avg req/sec 719.26 713.94 ⚠️ -5.32
/error-in-render failed reqs 0 0
/error-in-render total time (seconds) 1.652 1.62 -0.03
/error-in-render avg req/sec 1513.6 1543.4 +29.8
Client Bundles (main, webpack, commons)
vercel/next.js canary vercel/next.js fix/match-json-method-responses Change
450.HASH.js gzip 179 B 179 B
framework-HASH.js gzip 42.3 kB 42.3 kB
main-HASH.js gzip 27.3 kB 27.3 kB
webpack-HASH.js gzip 1.44 kB 1.44 kB
Overall change 71.3 kB 71.3 kB
Legacy Client Bundles (polyfills)
vercel/next.js canary vercel/next.js fix/match-json-method-responses Change
polyfills-HASH.js gzip 31 kB 31 kB
Overall change 31 kB 31 kB
Client Pages
vercel/next.js canary vercel/next.js fix/match-json-method-responses Change
_app-HASH.js gzip 1.35 kB 1.35 kB
_error-HASH.js gzip 180 B 180 B
amp-HASH.js gzip 305 B 305 B
css-HASH.js gzip 321 B 321 B
dynamic-HASH.js gzip 2.36 kB 2.36 kB
head-HASH.js gzip 342 B 342 B
hooks-HASH.js gzip 911 B 911 B
image-HASH.js gzip 4.89 kB 4.89 kB
index-HASH.js gzip 256 B 256 B
link-HASH.js gzip 2.19 kB 2.19 kB
routerDirect..HASH.js gzip 314 B 314 B
script-HASH.js gzip 375 B 375 B
withRouter-HASH.js gzip 309 B 309 B
85e02e95b279..7e3.css gzip 107 B 107 B
Overall change 14.2 kB 14.2 kB
Client Build Manifests
vercel/next.js canary vercel/next.js fix/match-json-method-responses Change
_buildManifest.js gzip 459 B 459 B
Overall change 459 B 459 B
Rendered Page Sizes
vercel/next.js canary vercel/next.js fix/match-json-method-responses Change
index.html gzip 531 B 531 B
link.html gzip 544 B 544 B
withRouter.html gzip 525 B 525 B
Overall change 1.6 kB 1.6 kB
Commit: ef76227

@husseinhere
Copy link

Thanks for doing this, it's very useful.

I guess like most fixes this is potentially a breaking change. Because res.json(null) does not work, I am hacking around the limitation with res.json("null") which gets sent as null. But with your fix, it's going to output "null"

Since you're just fixing a bug, you probably should just document it in the release notes? (i.e. There might be people out there who do something like this res.json(JSON.stringify(response, null, 2)) which now will be broken

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' },
})
}

timneutkens added a commit to timneutkens/next.js that referenced this pull request Apr 15, 2022
Continuation of vercel#33592 with updates tests / changes.

Co-Authored-By: Balázs Orbán <info@balazsorban.com>
@timneutkens
Copy link
Member

Applied the changes @ijjk suggested as they're correct. New PR: #36186

timneutkens added a commit that referenced this pull request Apr 15, 2022
Continuation of #33592 with updates tests / changes.

Co-Authored-By: Balázs Orbán <info@balazsorban.com>

Co-authored-by: Balázs Orbán <info@balazsorban.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 15, 2022
@balazsorban44 balazsorban44 deleted the fix/match-json-method-responses branch October 1, 2022 04:48
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

res.json("string") is not working as expected
4 participants