Repository navigation
fix(server): stream the request body when express 5 body-parser leaves req.body undefined - #7447
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
π Walkthrough
π₯ Pre-merge checks | β 4 | β 1
β¨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
π§Ή Nitpick comments (3)
packages/tests/server/regression/issue-7446-express5-body-parser-formdata.test.ts (3)
1-1: π Maintainability & Code Quality | π΅ Trivial | β‘ Quick winRename the test file to camelCase.
issue-7446-express5-body-parser-formdata.test.tsviolates the repository filename convention; retain the.test.tssuffix but use a camelCase filename.As per coding guidelines,
**/*.{ts,tsx,md,mdx}files must use camelCase names.π€ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/tests/server/regression/issue-7446-express5-body-parser-formdata.test.ts` at line 1, Rename the test file from its hyphenated name to a camelCase filename, preserving the issue identifier and the .test.ts suffix; no code changes are needed.Source: Coding guidelines
7-7: π Maintainability & Code Quality | π΅ Trivial | β‘ Quick winPrefer a namespace import for Zod.
Use
import * as z from 'zod'instead of a named validation-library import.As per coding guidelines, validation libraries should use namespace imports.
π€ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/tests/server/regression/issue-7446-express5-body-parser-formdata.test.ts` at line 7, Update the Zod import in the test file to use a namespace import, changing the named z import to the established `import * as z from 'zod'` form while preserving all existing z usage.Source: Coding guidelines
47-47: π Maintainability & Code Quality | π΅ Trivial | β‘ Quick winAvoid broad
anycasts in the regression test.
server.address() as any,fetch as any, andconst json: anydisable useful type checking. Narrow the server address toAddressInfo, use a typed fetch boundary ifnode-fetchrequires adaptation, and define the expected response shape.As per coding guidelines, prefer explicit typing over
anyand use type assertions sparingly.Also applies to: 57-57, 104-104
π€ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/tests/server/regression/issue-7446-express5-body-parser-formdata.test.ts` at line 47, Replace the broad any casts in the regression test with explicit types: narrow server.address() to AddressInfo, type the fetch adaptation at its boundary if node-fetch requires it, and define an interface or type for the expected response used by json. Update the affected server port, fetch, and response declarations while preserving the test behavior.Source: Coding guidelines
π€ Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@packages/tests/server/regression/issue-7446-express5-body-parser-formdata.test.ts`:
- Around line 29-80: Replace the suite-global startServer, beforeAll, afterAll,
and $ usage with testServerAndClientResource from
`@trpc/client/__tests__/testClientResource`. Configure express.json() and
express.urlencoded({ extended: true }) through the resourceβs server option,
then use await using ctx and reference ctx.httpUrl and ctx.client throughout the
test.
---
Nitpick comments:
In
`@packages/tests/server/regression/issue-7446-express5-body-parser-formdata.test.ts`:
- Line 1: Rename the test file from its hyphenated name to a camelCase filename,
preserving the issue identifier and the .test.ts suffix; no code changes are
needed.
- Line 7: Update the Zod import in the test file to use a namespace import,
changing the named z import to the established `import * as z from 'zod'` form
while preserving all existing z usage.
- Line 47: Replace the broad any casts in the regression test with explicit
types: narrow server.address() to AddressInfo, type the fetch adaptation at its
boundary if node-fetch requires it, and define an interface or type for the
expected response used by json. Update the affected server port, fetch, and
response declarations while preserving the test behavior.
πͺ Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
βΉοΈ Review info
βοΈ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: c9ed5630-81f8-4de7-8e2c-0ba9706f5e42
π Files selected for processing (3)
packages/server/src/adapters/node-http/incomingMessageToRequest.test.tspackages/server/src/adapters/node-http/incomingMessageToRequest.tspackages/tests/server/regression/issue-7446-express5-body-parser-formdata.test.ts
There was a problem hiding this comment.
Actionable comments posted: 1
π€ Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@packages/tests/server/regression/issue-7446-express5-body-parser-formdata.test.ts`:
- Around line 14-18: Update the z.custom<FormData> validator to safely reject
nullish and non-object inputs, verify that get is a function, and avoid calling
an untrusted toString directly; only accept values that satisfy these checks and
the intended FormData identification before the later input.get('id') usage.
πͺ Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
βΉοΈ Review info
βοΈ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 736e4e83-ba24-4649-9a7b-ccdad5fe10b4
π Files selected for processing (1)
packages/tests/server/regression/issue-7446-express5-body-parser-formdata.test.ts
@trpc/client
@trpc/next
@trpc/openapi
@trpc/react-query
@trpc/server
@trpc/tanstack-react-query
@trpc/upgrade
commit: |
## π― Changes Fixes a CI-only failure of `transforms.test.ts > hooks optimistic-update.tsx`: `Expected "Posts: 1initial", Received "Posts: 2initialFoo"` **at the initial-render assertion** β reproducible on unrelated PRs (the docs-only #7445, and #7447), always with `retry x2` all failing the same way. Two leaks between spec runs (the spec executes twice per test β input component and transformed snapshot β and again on CI retries), both via module-scoped state: 1. **In-flight mutation re-populates the server after reset.** The fixture's update is optimistic, so a spec run finishes (or fails) with the `create` mutation still in flight. `resetFixtureState()` truncates `posts`, then the late mutation settles and pushes `'Foo'` back β the next run's (or retry's) initial fetch returns `2initialFoo` for its whole `waitFor` window. Under CI load the settle reliably lands in that gap; on a fast local machine (where `retry` is 0 anyway) it practically never does, which is why this only ever failed in CI. The spec's disposer is now async (`makeAsyncResource` + `await using`) and waits for `queryClient.isMutating() === 0` before resetting. 2. **The shared `QueryClient` cache outlives a run.** `renderApp` now clears it before mounting, so a retry can't render the previous attempt's cached data. This covers all nine fixtures using the harness; no spec renders more than once per run, so nothing relied on cache persistence. ## β Checklist - [x] I have followed the steps listed in the [Contributing guide](https://github.com/trpc/trpc/blob/main/CONTRIBUTING.md). - [ ] If necessary, I have added documentation related to the changes made. - [x] I have added or updated the tests related to the changes made. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Tests** * Improved test isolation by resetting the appβs data cache before each render, preventing prior render or retry state from leaking into later tests. * Enhanced optimistic-update test cleanup by waiting for all in-flight mutations to fully complete before resetting fixture state and unmounting. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
68f556f to
6963154
Compare
There was a problem hiding this comment.
π§Ή Nitpick comments (1)
packages/tests/server/regression/issue-7446-express5-body-parser-formdata.test.ts (1)
46-56: π Maintainability & Code Quality | π΅ Trivial | β‘ Quick winReplace
anycasts with explicit types.The
server.address(), fetch adapter, and response JSON are all typed asany, weakening compile-time checks in this regression test. Add narrow types/guards for the server address, use the appropriate fetch type, and model the expected response shape.As per coding guidelines, prefer explicit typing over
any.Also applies to: 103-103
π€ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/tests/server/regression/issue-7446-express5-body-parser-formdata.test.ts` around lines 46 - 56, Replace the any casts in the server setup, httpBatchLink fetch configuration, and response JSON handling with explicit narrow types. In the server.address() callback, guard or narrow the address to the expected object containing a numeric port; use the projectβs appropriate fetch type for the adapter; and define the expected response shape before accessing it, preserving the regression test behavior without any casts.Source: Coding guidelines
π€ Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In
`@packages/tests/server/regression/issue-7446-express5-body-parser-formdata.test.ts`:
- Around line 46-56: Replace the any casts in the server setup, httpBatchLink
fetch configuration, and response JSON handling with explicit narrow types. In
the server.address() callback, guard or narrow the address to the expected
object containing a numeric port; use the projectβs appropriate fetch type for
the adapter; and define the expected response shape before accessing it,
preserving the regression test behavior without any casts.
βΉοΈ Review info
βοΈ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: aa5cf26c-8036-4c07-9c8b-ce8aa15d95c1
π Files selected for processing (3)
packages/server/src/adapters/node-http/incomingMessageToRequest.test.tspackages/server/src/adapters/node-http/incomingMessageToRequest.tspackages/tests/server/regression/issue-7446-express5-body-parser-formdata.test.ts
π§ Files skipped from review as they are similar to previous changes (2)
- packages/server/src/adapters/node-http/incomingMessageToRequest.test.ts
- packages/server/src/adapters/node-http/incomingMessageToRequest.ts
β¦ed (trpc#7706) <!-- CURSOR_AGENT_PR_BODY_BEGIN --> Confidence: high β a single branch that only runs for an ended stream without `req.body` (which previously always hung); full CI green. Fixes trpc#5534 ## Root cause `createBody` in `packages/server/src/adapters/node-http/incomingMessageToRequest.ts` only checked `req.readableEnded` when `req` had a `body` property. When another middleware drained the request stream without setting `req.body` (e.g. `@koa/bodyparser` without `patchNode`), it attached `data`/`end` listeners to a stream that had already ended, so any procedure reading its input waited forever. ## Fix When the stream has ended and `req` has no `body` property, `createBody` now returns a `ReadableStream` that errors immediately with a `TRPCError`. This is the same error-on-read approach the existing `PAYLOAD_TOO_LARGE` limit uses, so only procedures that actually read the body are affected. ## Behaviour - Mutations that read input fail fast with `INTERNAL_SERVER_ERROR`: "The request body has already been read by another middleware. Assign the parsed body to `req.body` so tRPC can use it". - Mutations without input still succeed. - It isn't treated as an empty body, because the input is genuinely lost. An empty body would surface as a confusing validation error, or a silent `undefined` for optional inputs. - `INTERNAL_SERVER_ERROR` because this is a server misconfiguration, not a client error. The message points to the same remedy as the issue (`patchNode` / assigning `req.body`). - Unchanged: `req.body` set to `undefined` on an ended stream still yields an empty body (trpc#7447). ## Tests - `packages/tests/server/regression/issue-5534-consumed-body-hang.test.ts`: a standalone server with a draining middleware. `ping` resolves `'pong'`; `echo('hello')` rejects with `INTERNAL_SERVER_ERROR` and the message above. Both calls keep a 2s hang guard. - `incomingMessageToRequest.test.ts`: an ended `POST` stream without `req.body` makes `request.text()` reject with the new error. - Both new tests fail without the fix (2s hang guard / 5s vitest timeout) and pass with it. - Locally: the regression test, node-http unit tests, standalone (including http2), express, fastify and next adapter tests, and the trpc#7446 regression test pass (9 files, 67 tests). `pnpm typecheck` passes for `packages/server` and `packages/tests`; eslint and prettier are clean. - CI: all checks pass. <!-- CURSOR_AGENT_PR_BODY_END --> <div><a href="https://cursor.com/agents/bc-9cf4eb23-1980-4dc1-bd36-ff50b58f3334?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-web-light.png"><img alt="Open in Web" width="114" height="28" src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a> <a href="https://cursor.com/background-agent?bcId=bc-9cf4eb23-1980-4dc1-bd36-ff50b58f3334&cursor_ref=pr_footer&cursor_cta=open_in_cursor"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img alt="Open in Cursor" width="131" height="28" src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a> </div> <!-- codesmith:footer --> --- <a href="https://app.blacksmith.sh/trpc/codesmith/trpc/pr/7706?autoLogin=true&ref=codesmith_pr_footer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-dark-v3.svg"><source media="(prefers-color-scheme: light)" srcset="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-light-v3.svg"><img alt="View with [code]smith" src="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-dark-v3.svg"></picture></a> <a href="https://backend.blacksmith.sh/track/enable-autofix?expires=1795049796&installation_model_id=443568&pr_number=7706&ref=codesmith_pr_footer&repository=trpc%2Ftrpc&return_to=https%3A%2F%2Fgithub.com%2Ftrpc%2Ftrpc%2Fpull%2F7706&signature=3afe1caf8f536a9b743dc54209dd34ac893888341b079bbfbf7e5a635d39eb04"><picture><source media="(prefers-color-scheme: dark)" srcset="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-light.svg"><img alt="Autofix with [code]smith" src="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-dark.svg"></picture></a> <sup>Need help on this PR? Tag <code>@codesmith-bot</code> with what you need.</sup> <!-- codesmith:autofix:disabled --> <!-- /codesmith:footer --> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Bug Fixes** - Requests whose body stream was consumed by middleware without assigning a parsed body now fail promptly with a clear internal error instead of hanging. - Input-based requests report that the request body has already been read and should be assigned to the request body property. - **Tests** - Added regression coverage for both direct request handling and server-level behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Cursor Agent <[email protected]>
|
This pull request has been locked because we are very unlikely to see comments on closed issues. If you think, this PR is still necessary, create a new one with the same branch. Thank you. |
Closes #7446
π― Changes
Bug fix. Express 5's body-parser defines
req.body(asundefined) even on content types it skips, e.g.multipart/form-data.createBody's'body' in reqpresence check then treated such requests as pre-parsed and built a body-lessRequest, sorequest.formData()failed withFailed to parse body as FormDatafor anyone running express 5 (including every NestJS app) with global body parsers registered.createBodynow only treats the request as pre-parsed whenreq.bodyholds a value. When the property exists but isundefined, it returns an empty body only if the stream was actually consumed (req.readableEnded) β preserving the existing tested behavior β and otherwise streams the untouched body exactly like a request no middleware saw. The pre-parsed string /IncomingMessage/ object paths are unchanged.Includes a regression test (express 5 + global body parsers + multipart mutation) that fails without the fix, plus a JSON mutation in the same app confirming the pre-parsed path still works. Full
@trpc/server(110) and@trpc/tests(541) suites pass.β Checklist
Summary by CodeRabbit
request.text()safely resolves to an empty string.undefined.undefinedpre-parsed body case after the stream ends.