Skip to content

fix(fastify): send object error bodies with a json content type - #18253

Merged
kamilmysliwiec merged 2 commits into
nestjs:masterfrom
maxymlyskov:fix/send-object-error-bodies-with-json-type
Oct 24, 2026
Merged

kamilmysliwiec merged 2 commits into
nestjs:masterfrom
maxymlyskov:fix/send-object-error-bodies-with-json-type

Conversation

@maxymlyskov

Copy link
Copy Markdown
Contributor

Context: sibling to 7dc6e34, which sends object error bodies as JSON from ExpressAdapter.reply(). This does the same for FastifyAdapter.reply()

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Other... Please describe:

What is the current behavior?

A route sets Content-Type: text/csv, then throws new NotFoundException({ code, message }). reply() only switches to application/json when body.statusCode >= 400 (fastify-adapter.ts#L767-L779), and a custom body has no statusCode, so the csv type stays. Fastify won't serialize a plain object under a non-JSON type without a reply serializer, so it throws FST_ERR_REP_INVALID_PAYLOAD_TYPE and the client gets a 500 in place of the 404.

Real HTTP on master, fastify 5.12.7. The built-in body has a statusCode and gets through, express answers the custom one fine:

PROBE master fastify /export.csv  status=500 content-type=application/json; charset=utf-8 body={"statusCode":500,"message":"Attempted to send payload of invalid type 'object'. Expected a string or Buffer."
PROBE master fastify /builtin.csv status=404 content-type=application/json; charset=utf-8 body={"message":"no such report","error":"Not Found","statusCode":404}
PROBE master express /export.csv  status=404 content-type=application/json; charset=utf-8 body={"code":"REPORT_NOT_FOUND","message":"no such report"}

Issue Number: N/A

Raw test output with fastify-adapter.ts from master:

 FAIL  packages/platform-fastify/test/adapters/fastify-adapter.spec.ts > FastifyAdapter > reply > should force a JSON content type for error bodies without a "statusCode"
AssertionError: expected "vi.fn()" to be called with arguments: [ 'Content-Type', 'application/json' ]
 FAIL  packages/platform-fastify/test/adapters/fastify-adapter.spec.ts > FastifyAdapter > reply > should answer a custom error body with its status on a route with a non-JSON content type
AssertionError: expected 500 to be 404 // Object.is equality
 Test Files  1 failed (1)
      Tests  2 failed | 5 passed | 127 skipped (134)

What is the new behavior?

reply() also forces application/json for an object body that isn't a stream (.pipe) or an ArrayBuffer view (Buffer, TypedArray) when the statusCode argument is 400 or more, the rule 7dc6e34 added to Express. It lives in an isErrorBody() helper next to isJsonContentType so reply() doesn't get more branches.

PROBE branch fastify /export.csv  status=404 content-type=application/json; charset=utf-8 body={"code":"REPORT_NOT_FOUND","message":"no such report"}
PROBE branch fastify /file.csv    status=200 content-type=text/csv body=id,name\n1,a\n

Text, Buffer and stream error bodies keep the route's type. Bodies with a statusCode, JSON and +json routes, and successful object bodies behave as before.

Does this PR introduce a breaking change?

  • Yes
  • No

Behaviour change, as in 7dc6e34: on a non-JSON route such an error reply is now labelled application/json and logs the existing "Content-Type doesn't match Reply body" warning. With a custom reply serializer, master sent it under the route's type.

Other information

Same condition as Express after 7dc6e34, and it extends the statusCode switch from #10474 (for #8469) to custom error bodies.

#18208 was a successful object reply on a non-JSON route, kept as plain Fastify does it, and this doesn't change it (/ok.csv still answers 500 on the branch). It only touches error replies, where the 500 hides the exception Nest is sending.

The 2 tests above fail on master and pass here; the related specs pass (166 tests), and prettier and oxlint are clean.

maxymlyskov and others added 2 commits October 24, 2026 04:23
FastifyAdapter.reply() replaced a non-JSON Content-Type set on the route
(e.g. with @Header() or in middleware) only when the body had a
statusCode of 400 or more. A custom HttpException body, as in
new NotFoundException({ code, message }), need not have one. Fastify
only serializes an object when the Content-Type is JSON or not set, so
it threw FST_ERR_REP_INVALID_PAYLOAD_TYPE and answered 500: the
exception's status and body were lost.

An object body sent with an error status code now gets the JSON
Content-Type too, as on Express since 7dc6e34. Streams and binary
bodies, which Fastify sends as they are, keep the route's type, and so
do text bodies. Behaviour change: on a route with a non-JSON
Content-Type, such a response is labelled application/json and logs the
same warning as error bodies with a statusCode already did.
@kamilmysliwiec
kamilmysliwiec merged commit 4103075 into nestjs:master Oct 24, 2026
4 checks passed
ttt43ttt pushed a commit to NoDevelopers/ts-monorepo that referenced this pull request Nov 22, 2026
| datasource | package                  | from   | to     |
| ---------- | ------------------------ | ------ | ------ |
| npm        | @nestjs/common           | 12.2.0 | 12.3.1 |
| npm        | @nestjs/core             | 12.2.0 | 12.3.1 |
| npm        | @nestjs/platform-express | 12.2.0 | 12.3.1 |


## [v12.3.1](nestjs/nest@v12.3.0...v12.3.1)



## [v12.3.0](https://github.com/nestjs/nest/releases/tag/v12.3.0)

#### v12.3.0 (2026-10-27)

##### Features

- `platform-node`
  - [#18063](nestjs/nest#18063) feat(node): add a native node http platform adapter ([@kamilmysliwiec](https://github.com/kamilmysliwiec))

##### Bug fixes

- `common`
  - [#18289](nestjs/nest#18289) fix(common): report the detected file type in file type errors ([@DenisCDev](https://github.com/DenisCDev))
  - [#18246](nestjs/nest#18246) fix(common): avoid throwing for arrow prototype constructors ([@fengxueweilai](https://github.com/fengxueweilai))
  - [#18220](nestjs/nest#18220) fix(common): abort the response when a streamable file fails midway ([@thekhegay](https://github.com/thekhegay))
- `core`
  - [#18276](nestjs/nest#18276) fix(core): run middleware once for routes that differ only in version ([@OmBhandwaldar](https://github.com/OmBhandwaldar))
  - [#18262](nestjs/nest#18262) fix(core): tolerate sse request sockets without tuning methods ([@SnowingFox](https://github.com/SnowingFox))
  - [#18252](nestjs/nest#18252) fix(core): read the url protocol from the server ([@thekhegay](https://github.com/thekhegay))
  - [#18254](nestjs/nest#18254) fix(core): name the array and index of undefined module entries ([@thekhegay](https://github.com/thekhegay))
  - [#18235](nestjs/nest#18235) fix(core): discover classes by each of their discovery decorators ([@OmBhandwaldar](https://github.com/OmBhandwaldar))
  - [#18216](nestjs/nest#18216) fix(core): read the abort on error option of the app being called ([@thekhegay](https://github.com/thekhegay))
  - [#18209](nestjs/nest#18209) fix(core): let middleware exclusions cover prefix-excluded routes ([@thekhegay](https://github.com/thekhegay))
  - [#18210](nestjs/nest#18210) fix(core): honor abortOnError passed to select() ([@Cayan](https://github.com/Cayan))
  - [#18215](nestjs/nest#18215) fix(core): subscribe to handler observables from other rxjs copies ([@koreahghg](https://github.com/koreahghg))
  - [#18201](nestjs/nest#18201) fix(core): read a quoted media type version in the middleware exclusions ([@hktitof](https://github.com/hktitof))
  - [#18200](nestjs/nest#18200) fix(core): resolve request-scoped forward refs for concurrent requests ([@maxymlyskov](https://github.com/maxymlyskov))
- `common`, `microservices`, `platform-ws`
  - [#18285](nestjs/nest#18285) fix(ws,microservices): load packages where bundlers can see them ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `common`, `microservices`, `websockets`
  - [#18272](nestjs/nest#18272) fix(common): keep one route param per argument in an overriding method ([@maxymlyskov](https://github.com/maxymlyskov))
- `platform-express`
  - [#18264](nestjs/nest#18264) fix(express): map unsupported multipart content types to 415 ([@seren-wib](https://github.com/seren-wib))
  - [#18234](nestjs/nest#18234) fix(express): end a head response for an empty streamable file ([@spokodev](https://github.com/spokodev))
  - [#18232](nestjs/nest#18232) fix(express): leave 5xx http-errors errors unmapped so they are logged ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#18214](nestjs/nest#18214) fix(platform-express): map http-errors exceptions to HttpException in Express adapter ([@okxint](https://github.com/okxint))
  - [#18199](nestjs/nest#18199) fix(express): send the standard body for an exception wrapping an error ([@KAPUIST](https://github.com/KAPUIST))
- `platform-fastify`
  - [#18253](nestjs/nest#18253) fix(fastify): send object error bodies with a json content type ([@maxymlyskov](https://github.com/maxymlyskov))
  - [#18240](nestjs/nest#18240) fix(fastify): leave 5xx fastify errors unmapped so they are logged ([@thekhegay](https://github.com/thekhegay))
  - [#18239](nestjs/nest#18239) fix(fastify): map 4xx http-errors errors to http exceptions ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#18226](nestjs/nest#18226) fix(fastify): listen on a file descriptor ([@thekhegay](https://github.com/thekhegay))
  - [#18217](nestjs/nest#18217) fix(fastify): run cors before nest middleware ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `core`, `platform-express`, `platform-fastify`, `platform-socket.io`, `platform-ws`, `websockets`
  - [#18251](nestjs/nest#18251) fix(core,express,fastify,ws,socket.io): load adapters with an older core ([@thekhegay](https://github.com/thekhegay))
- `microservices`
  - [#18250](nestjs/nest#18250) fix(microservices): re-arm the redis retries on a new listen ([@hktitof](https://github.com/hktitof))
  - [#18255](nestjs/nest#18255) fix(microservices): report a nats connection that gave up reconnecting ([@thekhegay](https://github.com/thekhegay))
  - [#18249](nestjs/nest#18249) fix(microservices): do not emit a trailing null to kafka requesters ([@thekhegay](https://github.com/thekhegay))
  - [#18256](nestjs/nest#18256) fix(microservices): let a retriable exception keep travelling ([@hktitof](https://github.com/hktitof))
  - [#18238](nestjs/nest#18238) fix(microservices): retry the tcp server again after close and listen ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#18223](nestjs/nest#18223) fix(microservices): clear the tcp retry timer when a new listen starts ([@hktitof](https://github.com/hktitof))
  - [#18221](nestjs/nest#18221) fix(microservices): honor mqtt topic filter boundaries ([@fabric0de](https://github.com/fabric0de))
  - [#18229](nestjs/nest#18229) fix(microservices): let only the exact message handler answer a request ([@maxymlyskov](https://github.com/maxymlyskov))
  - [#18211](nestjs/nest#18211) fix(microservices): fail the request when its last reply cannot be sent ([@maxymlyskov](https://github.com/maxymlyskov))
  - [#18206](nestjs/nest#18206) fix(microservices): reset the tcp retry attempts on each listen ([@hktitof](https://github.com/hktitof))
  - [#18204](nestjs/nest#18204) fix(microservices): count every failed rmq connection attempt ([@maxymlyskov](https://github.com/maxymlyskov))
  - [#18197](nestjs/nest#18197) fix(microservices): send the record headers of nats as message headers ([@hktitof](https://github.com/hktitof))

##### Dependencies

- `platform-express`
  - [#18268](nestjs/nest#18268) fix(deps): update dependency multer to v2.5.0 \[security] ([@renovate\[bot\]](https://github.com/apps/renovate))
- `common`
  - [#18257](nestjs/nest#18257) fix(deps): update dependency file-type to v22.2.0 ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `platform-fastify`
  - [#18219](nestjs/nest#18219) fix(deps): update dependency [@fastify/middie](https://github.com/fastify/middie) to v9.3.6 ([@renovate\[bot\]](https://github.com/apps/renovate))

##### Committers: 16

- Abdellatif Anaflous ([@hktitof](https://github.com/hktitof))
- Daniel Pinto ([@Cayan](https://github.com/Cayan))
- Denis Scarabelli ([@DenisCDev](https://github.com/DenisCDev))
- Junpei Zhang ([@pei711](https://github.com/pei711))
- Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- Luke Son ([@KAPUIST](https://github.com/KAPUIST))
- Maksym Lyskov ([@maxymlyskov](https://github.com/maxymlyskov))
- Om Bhandwaldar ([@OmBhandwaldar](https://github.com/OmBhandwaldar))
- Roman Khegay ([@thekhegay](https://github.com/thekhegay))
- Spoko Dev ([@spokodev](https://github.com/spokodev))
- [@fengxueweilai](https://github.com/fengxueweilai)
- [@okxint](https://github.com/okxint)
- snowingfox ([@SnowingFox](https://github.com/SnowingFox))
- yooseong ([@seren-wib](https://github.com/seren-wib))
- 김정현 (Kim JungHyeon) ([@fabric0de](https://github.com/fabric0de))
- 한국 ([@koreahghg](https://github.com/koreahghg))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants