diff --git a/packages/next/server/web/spec-extension/response.ts b/packages/next/server/web/spec-extension/response.ts index c34ba8a1df566ed..a82224e6643d474 100644 --- a/packages/next/server/web/spec-extension/response.ts +++ b/packages/next/server/web/spec-extension/response.ts @@ -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', + }, }) } diff --git a/test/unit/web-runtime/next-response.test.ts b/test/unit/web-runtime/next-response.test.ts index 293c33af06a87dc..98fe67b08f247af 100644 --- a/test/unit/web-runtime/next-response.test.ts +++ b/test/unit/web-runtime/next-response.test.ts @@ -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 () => { @@ -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,