diff --git a/packages/platform-fastify/adapters/fastify-adapter.ts b/packages/platform-fastify/adapters/fastify-adapter.ts index 1843b4ba90c..b3476b9da8d 100644 --- a/packages/platform-fastify/adapters/fastify-adapter.ts +++ b/packages/platform-fastify/adapters/fastify-adapter.ts @@ -532,9 +532,10 @@ export class FastifyAdapter< } body = body.getStream(); } + const responseContentType = fastifyReply.getHeader('Content-Type'); if ( - fastifyReply.getHeader('Content-Type') !== undefined && - fastifyReply.getHeader('Content-Type') !== 'application/json' && + typeof responseContentType === 'string' && + !responseContentType.startsWith('application/json') && body?.statusCode >= HttpStatus.BAD_REQUEST ) { Logger.warn( diff --git a/packages/platform-fastify/test/adapters/fastify-adapter.spec.ts b/packages/platform-fastify/test/adapters/fastify-adapter.spec.ts index 286e017816d..c4653ac0d22 100644 --- a/packages/platform-fastify/test/adapters/fastify-adapter.spec.ts +++ b/packages/platform-fastify/test/adapters/fastify-adapter.spec.ts @@ -54,6 +54,35 @@ describe('FastifyAdapter', () => { expect(reply.status).toHaveBeenCalledWith(statusCode); } }); + + it('should keep a JSON content type that carries parameters', () => { + const reply = createReply(); + reply.getHeader.mockReturnValue('application/json; charset=utf-8'); + + fastifyAdapter.reply( + reply as any, + { statusCode: 400, message: 'Oops' }, + 400, + ); + + expect(reply.header).not.toHaveBeenCalled(); + }); + + it('should force a JSON content type for error bodies sent with a non-JSON content type', () => { + const reply = createReply(); + reply.getHeader.mockReturnValue('text/html'); + + fastifyAdapter.reply( + reply as any, + { statusCode: 400, message: 'Oops' }, + 400, + ); + + expect(reply.header).toHaveBeenCalledWith( + 'Content-Type', + 'application/json', + ); + }); }); describe('mapException', () => {