Skip to content

Conversation

@chris-kreidl
Copy link

@chris-kreidl chris-kreidl commented Dec 10, 2025

Description

createClerkRequest in clerk/backend checks to see if args[0] is an instanceof ClerkRequest. If it is, it returns args[0] untouched. If not, it instantiates a new instance.

The TanStack Start middleware calls createClerkRequest using the return value of [patchRequest](https://github.com/clerk/javascript/blob/7b7c90f7a0c2258be62a8e851f9449772f7ee3cc/packages/react-router/src/server/utils.ts#L125-L140) as its argument. patchRequest returns an instance of Request

For some reason, one I haven't figured out yet, the check in createClerkRequest is accepting a Request instance and returning the Request untouched.

If I patch createClerkRequest to read as follows:

var createClerkRequest = (...args) => {
  // return args[0] instanceof ClerkRequest ? args[0] : new ClerkRequest(...args);
  const isClerkRequest = args[0] instanceof ClerkRequest;
  console.log('createClerkRequest debug:', {
    isClerkRequest,
    constructor: args[0]?.constructor?.name,
    hasClerkUrl: 'clerkUrl' in (args[0] || {}),
    hasCookies: 'cookies' in (args[0] || {}),
  });
  return isClerkRequest ? args[0] : new ClerkRequest(...args);
};

I am presented with the following:

createClerkRequest debug: {
  isClerkRequest: true,
  constructor: 'Request',
  hasClerkUrl: false,
  hasCookies: false
}

This PR refactors createClerkRequest to check for the keys that are unique to ClerkRequest as compared to Request, bypassing this apparently faulty instanceof check.

Fixes #6996

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 cookie initialization in authentication requests to prevent errors when using TanStack Start middleware.

✏️ Tip: You can customize this high-level summary in your review settings.

@changeset-bot
Copy link

changeset-bot bot commented Dec 10, 2025

🦋 Changeset detected

Latest commit: 4bb04af

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

This PR includes changesets to release 10 packages
Name Type
@clerk/backend Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/tanstack-react-start Patch
@clerk/testing 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 Dec 10, 2025

@chris-kreidl 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 Dec 10, 2025

Walkthrough

Fixes a bug in createClerkRequest where instanceof checks incorrectly allowed Request instances to pass through, preventing proper initialization of the cookies object. The detection logic now checks for presence of clerkUrl and cookies properties instead, ensuring cookies are properly created and resolving errors in downstream authentication contexts.

Changes

Cohort / File(s) Summary
Changelog
\.changeset/full-frogs-play\.md
Documents a patch fix for @clerk/backend addressing the createClerkRequest bug where instanceof checks allowed Request instances to bypass cookies initialization
Bug Fix
packages/backend/src/tokens/clerkRequest\.ts
Replaces instanceof ClerkRequest check with property-based detection: checks for non-null object with clerkUrl and cookies properties, returning the object if matched; otherwise creates a new ClerkRequest

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~5–10 minutes

  • Small, focused change in a single function with straightforward logic replacement
  • Clear rationale tied to the instanceof limitation across environments
  • Changelog entry is self-explanatory
  • Minimal risk; logic is easy to verify

Poem

🐰 A Request snuck past the old instanceof gate,
Cookies left undefined, sealing its fate.
Now we check for properties, clerkUrl in sight,
Cookies baked fresh—authentication made right! ✨

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 title accurately reflects the main change of refactoring the createClerkRequest function to fix the instanceof detection bug.
Linked Issues check ✅ Passed The PR fixes the TypeError in AuthenticateContext.getCookie by refactoring createClerkRequest to properly detect ClerkRequest objects using property checks instead of instanceof, directly addressing issue #6996.
Out of Scope Changes check ✅ Passed All changes are within scope: the changelog entry and createClerkRequest refactoring directly address the linked issue without introducing unrelated modifications.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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.

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: 0

🧹 Nitpick comments (2)
packages/backend/src/tokens/clerkRequest.ts (1)

84-90: Bugfix logic looks correct; consider extracting a proper type guard for ClerkRequest.

The new shape-based check on clerkUrl and cookies is a good way to avoid the unreliable instanceof behavior while still reusing an existing ClerkRequest when present. This should prevent raw Request instances from slipping through and aligns with the described TanStack Start failure path.

One refinement: instead of an inline isClerkRequest boolean plus as ClerkRequest cast, you can codify this as a dedicated type guard. That both documents the contract and lets TypeScript narrow correctly without a cast:

+const isClerkRequest = (value: unknown): value is ClerkRequest => {
+  return (
+    !!value &&
+    typeof value === 'object' &&
+    'clerkUrl' in value &&
+    'cookies' in value
+  );
+};
+
 export const createClerkRequest = (...args: ConstructorParameters<typeof ClerkRequest>): ClerkRequest => {
-  const isClerkRequest = args[0] && 
-    typeof args[0] === 'object' && 
-    'clerkUrl' in args[0] && 
-    'cookies' in args[0];
-  
-  return isClerkRequest ? args[0] as ClerkRequest : new ClerkRequest(...args);
+  if (isClerkRequest(args[0])) {
+    return args[0];
+  }
+
+  return new ClerkRequest(...args);
 };

This keeps the runtime behavior the same, removes the cast, and follows the guideline of using explicit isType(value: unknown): value is Type guards.

.changeset/full-frogs-play.md (1)

1-5: Minor wording/grammar polish for the changeset entry (optional).

The description is clear and accurate. You could tighten the last sentence a bit and add a period, which also addresses the “whether or not” style hint:

-Instead of checking `instanceof`, we check for the presence of the `cookies` and `clerkUrl` keys to determine whether or not we're dealing with a `Request` or `ClerkRequest`
+Instead of checking `instanceof`, we now check for the presence of the `cookies` and `clerkUrl` keys to determine whether we're dealing with a `Request` or `ClerkRequest`.

Purely stylistic; no need to block on this.

📜 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 7b7c90f and a044ff3.

📒 Files selected for processing (2)
  • .changeset/full-frogs-play.md (1 hunks)
  • packages/backend/src/tokens/clerkRequest.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

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

All code must pass ESLint checks with the project's configuration

Files:

  • packages/backend/src/tokens/clerkRequest.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • packages/backend/src/tokens/clerkRequest.ts
packages/**/src/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/backend/src/tokens/clerkRequest.ts
**/*.{ts,tsx,js,jsx}

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

Follow established naming conventions (PascalCase for components, camelCase for variables)

Files:

  • packages/backend/src/tokens/clerkRequest.ts
packages/**/src/**/*.{ts,tsx,js,jsx}

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

packages/**/src/**/*.{ts,tsx,js,jsx}: Maintain comprehensive JSDoc comments for public APIs
Use tree-shaking friendly exports
Validate all inputs and sanitize outputs
All public APIs must be documented with JSDoc
Use dynamic imports for optional features
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
Implement proper logging with different levels

Files:

  • packages/backend/src/tokens/clerkRequest.ts
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • packages/backend/src/tokens/clerkRequest.ts
**/*.{ts,tsx}

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

**/*.{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
Implement type guards for unknown types using the pattern function isType(value: unknown): value is Type
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 in classes
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Use mixins for shared behavior across unrelated classes in TypeScript
Use generic constraints with bounded type parameters like <T extends { id: string }>
Use utility types like Omit, Partial, and Pick for data transformation instead of manual type construction
Use discriminated unions instead of boolean flags for state management and API responses
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation at the type level
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Document functions with JSDoc comments including @param, @returns, @throws, and @example tags
Create custom error classes that extend Error for specific error types
Use the Result pattern for error handling instead of throwing exceptions
Use optional chaining (?.) and nullish coalescing (??) operators for safe property access
Let TypeScript infer obvious types to reduce verbosity
Use const assertions with as const for literal types
Use satisfies operator for type checking without widening types
Declare readonly arrays and objects for immutable data structures
Use spread operator and array spread for immutable updates instead of mutations
Use lazy loading for large types...

Files:

  • packages/backend/src/tokens/clerkRequest.ts
**/*.{js,ts,jsx,tsx}

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

Use ESLint with custom configurations tailored for different package types

Files:

  • packages/backend/src/tokens/clerkRequest.ts
**/*.{js,ts,jsx,tsx,json,md,yml,yaml}

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

Use Prettier for code formatting across all packages

Files:

  • packages/backend/src/tokens/clerkRequest.ts
🪛 LanguageTool
.changeset/full-frogs-play.md

[style] ~5-~5: Consider shortening this phrase to just ‘whether’, unless you mean ‘regardless of whether’.
Context: ...okiesandclerkUrlkeys to determine whether or not we're dealing with aRequestorCler...

(WHETHER)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: semgrep-cloud-platform/scan

@wobsoriano
Copy link
Member

Hello, thanks for this and the effort to find the issue!

I will open another PR to run the integration tests properly and add you as co-author and reference this PR.

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.

[@clerk/tanstack-react-start] Cannot read properties of undefined (reading 'get') in AuthenticateContext.getCookie

3 participants