Skip to content

Commit

Permalink
fix(NextResponse.json): pass options
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Mar 22, 2022
1 parent a2accb2 commit a2731d1
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
9 changes: 7 additions & 2 deletions packages/next/server/web/spec-extension/response.ts
Expand Up @@ -67,9 +67,14 @@ export class NextResponse extends Response {
return this.cookie(name, '', { expires: new Date(1), path: '/', ...opts })
}

static json(body: any) {
static json(body: any, init?: ResponseInit) {
const { headers, ...responseInit } = init || {}
return new NextResponse(JSON.stringify(body), {
headers: { 'content-type': 'application/json' },
...responseInit,
headers: {
...headers,
'content-type': 'application/json',
},
})
}

Expand Down
19 changes: 19 additions & 0 deletions test/unit/web-runtime/next-response.test.ts
Expand Up @@ -30,6 +30,7 @@ afterAll(() => {
const toJSON = async (response) => ({
body: await response.json(),
contentType: response.headers.get('content-type'),
status: response.status,
})

it('automatically parses and formats JSON', async () => {
Expand All @@ -42,6 +43,24 @@ it('automatically parses and formats JSON', async () => {
body: { message: 'hello!' },
})

expect(
await toJSON(NextResponse.json({ status: 'success' }, { status: 201 }))
).toMatchObject({
contentType: 'application/json',
body: { status: 'success' },
status: 201,
})

expect(
await toJSON(
NextResponse.json({ error: { code: 'bad_request' } }, { status: 400 })
)
).toMatchObject({
contentType: 'application/json',
body: { error: { code: 'bad_request' } },
status: 400,
})

expect(await toJSON(NextResponse.json(null))).toMatchObject({
contentType: 'application/json',
body: null,
Expand Down

0 comments on commit a2731d1

Please sign in to comment.