Skip to content

Conversation

@p9f
Copy link
Contributor

@p9f p9f commented Oct 17, 2025

Description

Should fix #7019.

I am not familiar with the codebase so please feel free to close if not appropriate.
But i took inspiration fromt a similar implementation in the @clerk/react-router (here), and this seems to fix the linked issue.

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • Bug Fixes

    • Fixed an issue where the middleware consumed request bodies, restoring proper downstream request handling.
  • Documentation

    • Added a changeset entry documenting the patch release.

@changeset-bot
Copy link

changeset-bot bot commented Oct 17, 2025

🦋 Changeset detected

Latest commit: 51741b2

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@clerk/tanstack-react-start Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@vercel
Copy link

vercel bot commented Oct 17, 2025

@p9f is attempting to deploy a commit to the Clerk Production Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 17, 2025

Walkthrough

Wraps incoming requests with a patched ClerkRequest in clerkMiddleware to avoid consuming the request body; updates loadOptions to accept a ClerkRequest type and reference its URL/clerkUrl for proxy and domain resolution; adds a changeset documenting the bug fix.

Changes

Cohort / File(s) Summary
Changeset documentation
\.changeset/full-horses-repair.md
Adds patch changeset documenting fix for clerkMiddleware consuming request body.
Middleware request patching
packages/tanstack-react-start/src/server/clerkMiddleware.ts
Imports and uses patchRequest to wrap args.request into a ClerkRequest, then passes the wrapped request to auth/load flows to avoid body consumption.
Load options signature & usage
packages/tanstack-react-start/src/server/loadOptions.ts
Changes loadOptions signature to accept ClerkRequest; updates logic to use request.url and request.clerkUrl for domain/isSatellite and proxy resolution; removes runtime creation/patching imports.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Middleware as clerkMiddleware
    participant Patch as patchRequest
    participant ClerkReq as ClerkRequest
    participant LoadOpts as loadOptions
    participant Handler as Route Handler

    Client->>Middleware: HTTP POST (with body)
    Middleware->>Patch: patchRequest(args.request)
    Patch-->>ClerkReq: wrapped ClerkRequest
    Middleware->>LoadOpts: loadOptions(ClerkRequest, ...)
    LoadOpts->>LoadOpts: read request.url / request.clerkUrl (no body read)
    Middleware->>Handler: forward original request to handler
    Handler->>Handler: safely read request.body
    Handler-->>Client: response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I patched the route with gentle care,
Wrapped the request so bodies spare —
Now handlers hop and parse with glee,
No eaten payloads, happy me! 🥕

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "fix(tanstack-react-start): Do not consume the body of the request in middleware" directly and clearly describes the primary change in the changeset. The changes implement a solution to prevent the clerkMiddleware from consuming the request body by wrapping the incoming request using createClerkRequest and patchRequest, which aligns perfectly with what the title communicates. The title is concise, specific, and avoids generic or vague terminology.
Linked Issues Check ✅ Passed The code changes address the primary requirement from issue #7019: preventing clerkMiddleware from consuming the request body to resolve the ERR_BODY_ALREADY_USED error. The implementation wraps the incoming request using patchRequest and createClerkRequest in clerkMiddleware.ts, allowing subsequent handlers to read the body. The loadOptions.ts parameter type update from Request to ClerkRequest is a necessary supporting change to accommodate the wrapped request type. The changeset entry properly documents this as a bug fix for the issue.
Out of Scope Changes Check ✅ Passed All changes in the pull request are directly related to fixing the request body consumption issue. The changeset entry documents the patch, clerkMiddleware.ts implements the request wrapping solution using patchRequest to prevent body consumption, and loadOptions.ts updates its parameter type to accept ClerkRequest which is necessary for the wrapper to function correctly. No unrelated modifications, refactoring, or scope creep is present.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@wobsoriano wobsoriano changed the title fix(tanstack-react-start): do not consume the body of the request in … fix(tanstack-react-start): Do not consume the body of the request in middleware Oct 17, 2025
Copy link
Member

@wobsoriano wobsoriano left a comment

Choose a reason for hiding this comment

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

good catch, thanks!

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d7c98af and 17377b3.

📒 Files selected for processing (2)
  • .changeset/full-horses-repair.md (1 hunks)
  • packages/tanstack-react-start/src/server/loadOptions.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • .changeset/full-horses-repair.md
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/tanstack-react-start/src/server/loadOptions.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/tanstack-react-start/src/server/loadOptions.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/tanstack-react-start/src/server/loadOptions.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/tanstack-react-start/src/server/loadOptions.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/tanstack-react-start/src/server/loadOptions.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/tanstack-react-start/src/server/loadOptions.ts
🧬 Code graph analysis (1)
packages/tanstack-react-start/src/server/loadOptions.ts (3)
packages/remix/src/ssr/loadOptions.ts (1)
  • loadOptions (13-88)
packages/tanstack-react-start/src/server/types.ts (1)
  • LoaderOptions (28-28)
packages/tanstack-react-start/src/utils/env.ts (1)
  • getPublicEnvVariables (4-25)
🔇 Additional comments (3)
packages/tanstack-react-start/src/server/loadOptions.ts (3)

1-1: LGTM: Type-only import is correct.

The change to import type is appropriate since ClerkRequest is used only as a type annotation. This follows TypeScript best practices and enables better tree-shaking.


28-33: Consistent usage of ClerkRequest properties.

The proxyUrl construction correctly uses request.clerkUrl (line 30), consistent with the updated function signature. This change aligns with the PR objective to avoid re-creating ClerkRequest internally (which could consume the request body).


20-22: ClerkRequest has both required properties—no issues found.

The verification confirms that ClerkRequest (extending Request) provides the url property through inheritance and explicitly defines clerkUrl as a readonly property. The code at lines 20-22 is type-safe and correct.


export const loadOptions = (request: Request, overrides: LoaderOptions = {}) => {
const clerkRequest = createClerkRequest(patchRequest(request));
export const loadOptions = (request: ClerkRequest, overrides: LoaderOptions = {}) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Add explicit return type annotation.

The function signature lacks an explicit return type. Per coding guidelines, public APIs should have explicit return types for clarity and to prevent unintended type widening.

As per coding guidelines.

Apply this diff:

-export const loadOptions = (request: ClerkRequest, overrides: LoaderOptions = {}) => {
+export const loadOptions = (request: ClerkRequest, overrides: LoaderOptions = {}): ReturnType<typeof loadOptions> => {

Alternatively, define an explicit interface for the return type:

interface LoadOptionsResult {
  secretKey: string;
  machineSecretKey?: string;
  publishableKey: string;
  jwtKey?: string;
  apiUrl: string;
  domain: string;
  isSatellite: boolean;
  proxyUrl?: string;
  signInUrl: string;
  signUpUrl: string;
  afterSignInUrl: string;
  afterSignUpUrl: string;
  // ... other properties from overrides
}

export const loadOptions = (request: ClerkRequest, overrides: LoaderOptions = {}): LoadOptionsResult => {

Note: This change from Request to ClerkRequest is a breaking API change. Ensure this is documented in the changeset.

@jacekradko jacekradko merged commit 2a815eb into clerk:main Oct 17, 2025
7 of 8 checks passed
NicolasLopes7 pushed a commit that referenced this pull request Oct 23, 2025
…middleware (#7020)

Co-authored-by: Robert Soriano <sorianorobertc@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[@clerk/tanstack-react-start] ERR_BODY_ALREADY_USED when using with bun

4 participants