Skip to content

fix(microservices): do not treat foreign JSON as an RPC envelope - #17670

Merged
kamilmysliwiec merged 1 commit into
nestjs:masterfrom
xia-chao:fix/incoming-response-require-packet-id
Sep 14, 2026
Merged

kamilmysliwiec merged 1 commit into
nestjs:masterfrom
xia-chao:fix/incoming-response-require-packet-id

Conversation

@xia-chao

@xia-chao xia-chao commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

PR Checklist

PR Type

  • 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?

If a microservice reply is a normal JSON object that happens to have a field named response, ClientProxy does not return that object. It only returns the value of that one field.

That is wrong when the other side is not Nest. Nest wraps its own replies in a small envelope (id + response / err / isDisposed). The deserializer currently treats any object with a response (or err, or isDisposed) key as that envelope, even when there is no packet id.

So a NATS (or Redis / MQTT / TCP / RMQ) payload like { "code": "SMF-8000-YX", "response": "the service is in maintenance" } comes out as the string "the service is in maintenance".

Issue Number: #17669

Why this fix

A real Nest packet always has an id. That is part of the type: IncomingResponse = WritePacket & PacketId.

The old check only asked "does this object have a response key?". A business payload can have that key too. The new check asks "does this look like a Nest envelope?": it must have an id and one of the envelope fields.

That is the smallest change that matches the type, keeps the existing official tests green, and returns the full object for #17669.

We did not make this NATS-only. The same deserializer is the default on the other transports, so they would hit the same bug.

We also did not require isDisposed to be present. The official tests already treat { id, response } as an internal packet.

What is the new behavior?

  • Nest-to-Nest replies (id + response / err / isDisposed) are unchanged.
  • A foreign payload with a response field but no packet id is treated as the actual reply body.
  • Added a test for that case.

Does this PR introduce a breaking change?

  • Yes
  • No

Callers who relied on ClientProxy stripping a foreign response field were already getting a corrupted body. They now get the full object.

One leftover: a foreign payload that has both id and response still looks like an envelope. That is rarer than #17669 and is not changed here.

Other information

incoming-response.deserializer.spec.ts covers the old cases plus the #17669 shape.

@micalevisk micalevisk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR and for the clear write-up. The problem in #17669 is real, and I agree the current isExternal() heuristic is too loose. Unfortunately the chosen discriminator (id must be present) breaks a first-party transporter, so I have to request changes.

🔴 Blocking: this breaks Nest-to-Nest request/response over RabbitMQ

ServerRMQ never stamps id into the reply body. Correlation is done with the AMQP correlationId property, and sendMessage() serializes exactly what Server#send() hands it: { response }, { err } and { isDisposed: true } (only the "no handler" packet carries an id, see server-rmq.ts). Every other built-in server does Object.assign(response, { id }), RMQ does not.

With this PR, every regular RMQ reply is now treated as "foreign":

{"response":42}     => {"response":{"response":42},"isDisposed":true}
{"err":"boom"}      => {"response":{"err":"boom"},"isDisposed":true}
{"isDisposed":true} => {"response":{"isDisposed":true},"isDisposed":true}

So an RMQ client.send() consumer receives { response: 42 } instead of 42, a thrown RpcException resolves successfully with { err: ... } as the value, and the completion packet emits a spurious { isDisposed: true } value. That is a hard breaking change for one of the most used transports.

This is exactly what CI is reporting: build-and-test is red, and locally packages/microservices/test/client/client-rmq.spec.ts fails 3 tests (handleMessage > when error / when disposed / when response). The PR description says "keeps the existing official tests green", so please re-run the full pnpm test before pushing again.

Note also that stamping id in ServerRMQ would not be enough on its own: a client upgraded to a version with this check, talking to a server on an older @nestjs/microservices version, would still break. Requiring id is effectively a wire-protocol change for RMQ, which we cannot ship in a patch.

Suggested direction

If you want to keep iterating on this, a discriminator that does not depend on id would avoid the compatibility problem. One option: treat the value as a Nest envelope only when all of its keys belong to the envelope (id, err, response, isDisposed, status). Nest packets never carry extra keys, whereas the payload in #17669 has uuid, code, eventType, etc. That fixes the reported case on every transport, keeps old servers compatible, and does not change the existing RMQ behavior. It is still a heuristic (a foreign { response: "..." } with no other keys stays ambiguous), so it should be discussed with @kamilmysliwiec before you invest in it. Keep in mind the deserializer client option already exists as the escape hatch for interop with non-Nest services, and that has historically been the recommended answer for this class of problem.

Tests

  • The new spec only covers the response key. If a heuristic change lands, please add the symmetric cases for err and isDisposed without id, and a direct isExternal() case for { id, isDisposed: true } (server completion packet) so the envelope contract is pinned down.
  • Please add an RMQ-shaped case ({ response } without id) to incoming-response.deserializer.spec.ts so this regression cannot come back silently.

Minor

  • Inline issue references are uncommon in this codebase (grep -rn "nestjs/nest#" packages only hits this line). The existing precedent is // @see https://github.com/nestjs/nest/issues/...; I would either use that form or drop the reference and keep the comment focused on the invariant.
  • id: undefined in the new toEqual expectation is a no-op (toEqual ignores undefined props). Either use toStrictEqual or drop the key, so the test states what it actually asserts.
  • looksLikeWritePacket is computed even when hasPacketId is false. An early if (!hasPacketId) return true; reads closer to the intent. Cosmetic.
  • IncomingResponseDeserializer is @publicApi and is extended by NatsResponseJSONDeserializer and user code. Changing the semantics of isExternal() needs to be called out in the changelog either way.

Follow-ups (not for this PR)

  • IncomingRequestDeserializer.isExternal() has the mirrored weakness on the server side: any foreign request with a data or pattern key is treated as a Nest packet. Worth an issue.
  • ServerRMQ not stamping id in the reply body is an inconsistency with the other servers and is the reason this heuristic cannot be tightened around id. Also worth an issue, even if the fix has to wait for a major.

Prior art

For context, isExternal() has not been touched since it was introduced in #2653 (2019, "allow to adapt external services with schema expected by NestJS"), and no earlier PR proposed anchoring it on id. There is no explicit "won't fix" on the response side. The closest maintainer statements are:

  • #13675 (request side, 2024): the pattern/data shape is "the unified schema & behavior between all transport strategies", i.e. by design, with the custom serializer/deserializer options as the interop escape hatch (#2653, #4017).
  • #3986 (2020) relaxed the NATS client to message.id && message.id !== packet.id precisely because "a response without an id will only happen when accepting a response message from an external source". That statement was made for NATS and does not hold for RMQ, as shown above.
  • #17672 is the request-side sibling of this PR and is being reviewed in parallel. Whatever discriminator we settle on should be consistent across both.

@xia-chao

xia-chao commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor Author

You're right!
I checked server-rmq.ts and the reply body really is just { response } / { err } / { isDisposed: true } — the id goes in the AMQP correlationId. So my check would have double-wrapped every RMQ reply. My "tests are green" claim was wrong too, I hadn't run the whole suite. Dropping the id idea.

The key-set check does fix what I reported ({ uuid, code, response, eventType } comes back whole) and leaves RMQ alone. Only a bare { response: "..." } from a non-Nest service is still swallowed.

@kamilmysliwiec before I rewrite it — is a key-based guess OK for a @publicapi method that NatsResponseJSONDeserializer and user code inherit? Or is "configure the deserializer" the intended answer, in which case I'll close this and leave #17669 as-is.

And should #17672 use the same rule?

If yes, I'll take your nits and the tests you listed.

@xia-chao
xia-chao requested a review from micalevisk September 13, 2026 07:45

@micalevisk micalevisk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A Nest packet only carries envelope keys (`id`, `err`, `response`,
`isDisposed`, `status`). A payload with any other key is a foreign message
and must be delivered as-is instead of being unwrapped.

Closes nestjs#17669
@xia-chao
xia-chao force-pushed the fix/incoming-response-require-packet-id branch from e83d5ee to 36f6397 Compare September 13, 2026 16:17
@xia-chao

xia-chao commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor Author

@micalevisk
Green now. Used your key-set idea — a value is only a packet if all its keys are
id, err, response, isDisposed or status. Reproduced the 9 RMQ failures
locally first, then ran the other transports and the unit suite: all pass.

Only gap left is a bare { response: "..." }, same ambiguity you mentioned.

@xia-chao
xia-chao requested a review from micalevisk September 13, 2026 17:39
@kamilmysliwiec
kamilmysliwiec merged commit b2b555a into nestjs:master Sep 14, 2026
3 checks passed
@kamilmysliwiec

Copy link
Copy Markdown
Member

lgtm

ttt43ttt pushed a commit to NoDevelopers/ts-monorepo that referenced this pull request Nov 22, 2026
| datasource | package                  | from   | to     |
| ---------- | ------------------------ | ------ | ------ |
| npm        | @nestjs/common           | 12.0.1 | 12.1.0 |
| npm        | @nestjs/core             | 12.0.1 | 12.1.0 |
| npm        | @nestjs/platform-express | 12.0.1 | 12.1.0 |


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

##### v12.1.0 (2026-09-23)

##### Bug fixes

- `core`
  - [#17838](nestjs/nest#17838) fix(core): inherit optional ctor params when the ctor is not redeclared ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17819](nestjs/nest#17819) fix(core): name the module when metadata entries are invalid ([@thekhegay](https://github.com/thekhegay))
- `microservices`
  - [#17828](nestjs/nest#17828) fix(microservices): let the redis client retry after a failed connect ([@hktitof](https://github.com/hktitof))
  - [#17810](nestjs/nest#17810) fix(microservices): fail every pending request when a callback throws ([@hktitof](https://github.com/hktitof))

##### Enhancements

- `core`
  - [#17846](nestjs/nest#17846) fix(core): do not skip subsequent middleware after a transient one ([@lehafari](https://github.com/lehafari))
  - [#17840](nestjs/nest#17840) fix(core): preserve route handler names ([@Grmiade](https://github.com/Grmiade))
- `common`, `core`
  - [#17713](nestjs/nest#17713) feat(core): add support for array of global prefixes ([@micalevisk](https://github.com/micalevisk))
  - [#17834](nestjs/nest#17834) feat(common,core): add built-in, adapter-agnostic cookies ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `platform-fastify`
  - [#17824](nestjs/nest#17824) fix(fastify): honor Nest forceCloseConnections in initHttpServer ([@xia-chao](https://github.com/xia-chao))
- `common`
  - [#17827](nestjs/nest#17827) fix(common): apply the ParseDatePipe default to every missing value ([@xia-chao](https://github.com/xia-chao))
- `platform-fastify`, `testing`
  - [#17835](nestjs/nest#17835) feat(fastify): add file upload interceptors backed by [@fastify/multipart](https://github.com/fastify/multipart) ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `common`, `core`, `platform-fastify`
  - [#17836](nestjs/nest#17836) feat(common,core,fastify): built-in CSRF protection and security headers ([@kamilmysliwiec](https://github.com/kamilmysliwiec))

##### Committers: 9

- Abdellatif Anaflous ([@hktitof](https://github.com/hktitof))
- Alejandro ([@lehafari](https://github.com/lehafari))
- Chris Z ([@haimingZZ](https://github.com/haimingZZ))
- Johnny J. Huirilef Millán ([@johnnyhuirilef](https://github.com/johnnyhuirilef))
- Jérémy Fauvel ([@Grmiade](https://github.com/Grmiade))
- Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- Micael Levi L. Cavalcante ([@micalevisk](https://github.com/micalevisk))
- Roman Khegay ([@thekhegay](https://github.com/thekhegay))
- Xia Chao ([@xia-chao](https://github.com/xia-chao))


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

##### v12.0.4 (2026-09-21)

##### Bug fixes

- `microservices`
  - [#17816](nestjs/nest#17816) fix(microservices): let the kafka client retry after a failed connect ([@Xch4rt](https://github.com/Xch4rt))
  - [#17786](nestjs/nest#17786) fix(microservices): fail pending rmq requests on client close ([@johnnyhuirilef](https://github.com/johnnyhuirilef))
  - [#17802](nestjs/nest#17802) fix(microservices): fail pending nats requests on client close ([@hktitof](https://github.com/hktitof))
  - [#17803](nestjs/nest#17803) fix(microservices): handle missing grpc package namespace gracefully ([@Se3do](https://github.com/Se3do))
  - [#17799](nestjs/nest#17799) fix(microservices): share the processing hook envelope across transports ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17797](nestjs/nest#17797) fix(microservices): close the kafka request-response span exactly once ([@MingLin1995](https://github.com/MingLin1995))
  - [#17794](nestjs/nest#17794) fix(microservices): close the request-response span exactly once ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17785](nestjs/nest#17785) fix(microservices): route message handler rejections to handleError ([@hktitof](https://github.com/hktitof))
- `core`
  - [#17821](nestjs/nest#17821) fix(core): hang on sparse factory inject array ([@xia-chao](https://github.com/xia-chao))

##### Enhancements

- `platform-express`
  - [#17818](nestjs/nest#17818) Fix: merge multer `limits` key-by-key instead of overriding it wholesale ([@mdrezuanislamridoy](https://github.com/mdrezuanislamridoy))
- `common`
  - [#17780](nestjs/nest#17780) fix(common): mark parse date pipe options as optional ([@Chy-Zaber-Bin-Zahid](https://github.com/Chy-Zaber-Bin-Zahid))

##### Dependencies

- `common`
  - [#17793](nestjs/nest#17793) fix(deps): update dependency file-type to v22.1.1 ([@renovate\[bot\]](https://github.com/apps/renovate))
- `platform-fastify`
  - [#17791](nestjs/nest#17791) fix(deps): update dependency fastify to v5.12.5 ([@renovate\[bot\]](https://github.com/apps/renovate))

##### Committers: 10

- Abdellatif Anaflous ([@hktitof](https://github.com/hktitof))
- Chowdhury Zaber Bin Zahid ([@Chy-Zaber-Bin-Zahid](https://github.com/Chy-Zaber-Bin-Zahid))
- Imad - Prakticode ([@prakticode](https://github.com/prakticode))
- Johnny J. Huirilef Millán ([@johnnyhuirilef](https://github.com/johnnyhuirilef))
- Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- MD. Ridoy Babu ([@mdrezuanislamridoy](https://github.com/mdrezuanislamridoy))
- Ming ([@MingLin1995](https://github.com/MingLin1995))
- Mohammed Said ([@Se3do](https://github.com/Se3do))
- Pablo Gutiérrez ([@Xch4rt](https://github.com/Xch4rt))
- Xia Chao ([@xia-chao](https://github.com/xia-chao))


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

##### v12.0.3 (2026-09-15)

##### Bug fixes

- `microservices`
  - [#17766](nestjs/nest#17766) fix(microservices): always run the kafka processing end hook ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17757](nestjs/nest#17757) fix(microservices): fail pending requests on client close ([@hktitof](https://github.com/hktitof))
  - [#17746](nestjs/nest#17746) fix(microservices): bound memory held for a TCP peer ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17745](nestjs/nest#17745) fix(microservices): destroy open TCP sockets on shutdown ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `common`
  - [#17738](nestjs/nest#17738) fix(common): validate uuid version and variant when no version is set ([@otnc](https://github.com/otnc))
  - [#17761](nestjs/nest#17761) fix(common): invoke proto-key stripping hook via this in transform ([@koreahghg](https://github.com/koreahghg))

##### Dependencies

- `platform-express`
  - [#17762](nestjs/nest#17762) fix(deps): update dependency multer to v2.4.0 ([@renovate\[bot\]](https://github.com/apps/renovate))
- `common`
  - [#17753](nestjs/nest#17753) fix(deps): update dependency file-type to v22.1.0 ([@renovate\[bot\]](https://github.com/apps/renovate))

##### Committers: 4

- Abdellatif Anaflous ([@hktitof](https://github.com/hktitof))
- Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- otoneko. ([@otnc](https://github.com/otnc))
- 한국 ([@koreahghg](https://github.com/koreahghg))


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

##### v12.0.2 (2026-09-14)

##### Bug fixes

- `platform-socket.io`, `platform-ws`
  - [#17666](nestjs/nest#17666) fix(socket.io): keep the message stream alive when a handler throws ([@hktitof](https://github.com/hktitof))
- `microservices`
  - [#17728](nestjs/nest#17728) fix(microservices): detach signal listeners of connected microservices ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17671](nestjs/nest#17671) fix(microservices): fail requests whose reply subscription is rejected ([@samuelmbabhazi](https://github.com/samuelmbabhazi))
  - [#17670](nestjs/nest#17670) fix(microservices): do not treat foreign JSON as an RPC envelope ([@xia-chao](https://github.com/xia-chao))
  - [#17644](nestjs/nest#17644) fix(microservices): don't flatten plain handler results with pre-request hooks ([@iamolegga](https://github.com/iamolegga))
  - [#17641](nestjs/nest#17641) fix(microservices): run the mqtt listen callback once ([@johnnyhuirilef](https://github.com/johnnyhuirilef))
- `common`
  - [#17710](nestjs/nest#17710) fix(common): collapse duplicate internal slashes in `normalizePath` ([@Asadshah7950](https://github.com/Asadshah7950))
  - [#17655](nestjs/nest#17655) fix(common): validate UUID v3 variant ([@gwagjiug](https://github.com/gwagjiug))
  - [#17702](nestjs/nest#17702) fix(common): treat empty string as array input in ParseArrayPipe ([@xia-chao](https://github.com/xia-chao))
- `core`
  - [#17667](nestjs/nest#17667) fix(core): discover factory providers with discovery decorators ([@hktitof](https://github.com/hktitof))
  - [#17709](nestjs/nest#17709) fix(core): avoid treating error instances with `statusCode` as http errors ([@Asadshah7950](https://github.com/Asadshah7950))
  - [#17625](nestjs/nest#17625) fix(core): clean up repeated shutdown signal listeners ([@Raj4478](https://github.com/Raj4478))
- `platform-fastify`
  - [#17705](nestjs/nest#17705) fix(fastify): derive neutral version when accept header is absent ([@Gaurav1112](https://github.com/Gaurav1112))
  - [#17699](nestjs/nest#17699) fix(fastify): send responses for exceptions thrown from middleware ([@micalevisk](https://github.com/micalevisk))

##### Enhancements

- `microservices`
  - [#17734](nestjs/nest#17734) feat(microservices): add maxConnectionAttempts to ServerMqtt ([@kamilmysliwiec](https://github.com/kamilmysliwiec))

##### Dependencies

- `platform-fastify`
  - [#17729](nestjs/nest#17729) fix(deps): update dependency fastify to v5.12.4 ([@renovate\[bot\]](https://github.com/apps/renovate))

##### Committers: 16

- Abdellatif Anaflous ([@hktitof](https://github.com/hktitof))
- Alexey Solovyov ([@lyohaplotinka](https://github.com/lyohaplotinka))
- Asad Ali Shah ([@Asadshah7950](https://github.com/Asadshah7950))
- Gyeonghun Park ([@Gyeonghun-Park](https://github.com/Gyeonghun-Park))
- Johnny J. Huirilef Millán ([@johnnyhuirilef](https://github.com/johnnyhuirilef))
- Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- Kumar Gaurav ([@Gaurav1112](https://github.com/Gaurav1112))
- Micael Levi L. Cavalcante ([@micalevisk](https://github.com/micalevisk))
- Ming ([@MingLin1995](https://github.com/MingLin1995))
- Mohammed Said ([@Se3do](https://github.com/Se3do))
- Rajeshwar Singh  ([@Raj4478](https://github.com/Raj4478))
- Xia Chao ([@xia-chao](https://github.com/xia-chao))
- [@iamolegga](https://github.com/iamolegga)
- cui fliter ([@cuishuang](https://github.com/cuishuang))
- samuel mbabhazi ([@samuelmbabhazi](https://github.com/samuelmbabhazi))
- 곽지욱 ([@gwagjiug](https://github.com/gwagjiug))
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.

3 participants