Skip to content

Conversation

wobsoriano
Copy link
Member

@wobsoriano wobsoriano commented Sep 26, 2025

Description

This PR introduces a new clerkMiddleware() replacing the custom server handler.

DX Guide

For beta testers:

Installation

To test this, use the snapshot version of Clerk's TanStack React Start SDK:

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6859

Setup

Create a src/start.ts file and add clerkMiddleware() to the list of request middlewares:

// src/start.ts
import { clerkMiddleware } from '@clerk/tanstack-react-start/server'

export const startInstance = createStart(() => {
  return {
    requestMiddleware: [clerkMiddleware()],
  }
})

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

  • New Features

    • Added a global Clerk middleware for TanStack Start v1 RC.
    • Introduced auth() for server use; getAuth can be used without a Request.
    • ClerkProvider initialization now uses the global start context.
  • Templates

    • Starter updated to register middleware in start.ts, remove legacy server bootstrap, and adapt router naming.
  • Documentation

    • Added a changeset with setup and usage guidance.
  • Chores

    • Upgraded TanStack packages and Vite; added Vite React plugin.
    • CI integration test matrix adjusted to skip a router test.

Copy link

changeset-bot bot commented Sep 26, 2025

🦋 Changeset detected

Latest commit: 67e99da

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 Minor

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

Copy link

vercel bot commented Sep 26, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Oct 9, 2025 8:02pm

Copy link
Contributor

coderabbitai bot commented Sep 26, 2025

Walkthrough

Migrates TanStack React Start integration to a global Clerk middleware and context. Adds clerkMiddleware and auth() (no-request) APIs, updates getAuth to use the global start context, changes client initial-state wiring, updates integration templates, and bumps related dependencies and build tooling.

Changes

Cohort / File(s) Summary
Deps & build tooling
packages/tanstack-react-start/package.json, integration/templates/tanstack-react-start/package.json, integration/templates/tanstack-react-start/vite.config.ts, .github/workflows/ci.yml, .changeset/spotty-cooks-march.md
Bump TanStack packages to 1.132.x, add @vitejs/plugin-react, update Vite, comment out an integration CI matrix entry, and add a changeset documenting the middleware-based integration.
Client Clerk initial state
packages/tanstack-react-start/src/client/ClerkProvider.tsx
Switch Clerk initial-state source from router context to global start context; serialize global clerkInitialState into window.__clerk_init_state with a window fallback retained.
Server auth middleware & API
packages/tanstack-react-start/src/server/clerkMiddleware.ts, packages/tanstack-react-start/src/server/auth.ts, packages/tanstack-react-start/src/server/getAuth.ts, packages/tanstack-react-start/src/server/index.ts, packages/tanstack-react-start/src/server/types.ts, packages/tanstack-react-start/src/server/utils/index.ts, packages/tanstack-react-start/src/utils/errors.ts, packages/tanstack-react-start/src/utils/env.ts
Add clerkMiddleware implementing per-request authentication (authenticateRequest, Netlify dev handshake handling, header propagation, context enrichment with clerkInitialState and auth helper); add auth() (no-request) helper; refactor getAuth to use global start context and new error; expose auth and clerkMiddleware from server index; rename/alias middleware option types; change getResponseClerkState to return only clerkInitialState; rename error constant to clerkMiddlewareNotConfigured; simplify getPublicEnvVariables signature.
Integration template migration & router updates
integration/templates/tanstack-react-start/src/server.tsx, integration/templates/tanstack-react-start/src/start.ts, integration/templates/tanstack-react-start/src/routes/user.tsx, integration/templates/tanstack-react-start/src/router.tsx
Remove the custom server handler bootstrap; add start.ts to register clerkMiddleware() via createStart; update routes to use auth() directly; rename router factory export from createRoutergetRouter and update module augmentation/imports.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant Server
  participant Start as TanStack Start
  participant MW as clerkMiddleware
  participant Clerk as Clerk Backend

  Client->>Server: HTTP Request
  Server->>Start: invoke start instance
  Start->>MW: run request middleware
  MW->>Clerk: authenticateRequest(req, acceptAnyToken)
  alt Netlify dev cache handshake
    Clerk-->>MW: Response with Location + headers
    MW-->>Start: trigger 307 redirect (propagate Clerk headers)
    Start-->>Client: 307 Redirect with Clerk headers
  else Normal auth flow
    Clerk-->>MW: Auth state + headers
    MW->>Start: next({ ctx += { clerkInitialState, auth } })
    Start->>Server: Route/loaders/actions execute with ctx.auth
    MW->>Start: copy Clerk headers to final response
    Start-->>Client: Final Response
  end
Loading
sequenceDiagram
  autonumber
  participant SSR as Server Render
  participant GSC as Global Start Context
  participant CP as ClerkProvider
  participant Script as ScriptOnce

  SSR->>GSC: Provide clerkInitialState
  SSR->>CP: Render with clerkInitState = GSC.clerkInitialState
  SSR->>Script: window.__clerk_init_state = clerkInitialState
  Note over CP,Script: Client fallback reads window.__clerk_init_state if present
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

A hop, a skip, middleware in line,
I wired the auth so routes align.
Global carrots in context state,
No request needed—flows integrate.
Router renamed, builds refined—🥕🐇

Pre-merge checks and finishing touches

✅ Passed checks (3 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 primary changes in this pull request by stating the feature scope (tanstack-react-start) and core updates (middleware introduction and support for TanStack Start RC). It follows conventional commit style, clearly indicating a feature addition and the relevant package. The phrasing is concise, specific, and aligns with the modifications in the PR summary.
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
  • Commit unit tests in branch rob/tanstack-rc

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: 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 8e8bfb5 and 1c717f5.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (1)
  • packages/tanstack-react-start/package.json (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{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/package.json
packages/*/package.json

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

All publishable packages should be placed under the packages/ directory

packages/*/package.json: All publishable packages must be located in the 'packages/' directory.
All packages must be published under the @clerk namespace on npm.
Semantic versioning must be used across all packages.

Files:

  • packages/tanstack-react-start/package.json
⏰ 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). (6)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)

Comment on lines +84 to +85
"@tanstack/react-router": "^1.132.0",
"@tanstack/react-start": "^1.132.0",
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Raising the peer dependency floor is a breaking change

Moving the peer requirements to ^1.132.0 drops support for every app still on 1.131.x, which our previous range accepted. That’s effectively a breaking change for consumers, so we either need to widen the range (e.g. >=1.131.49 <2) if compatibility remains, or else communicate the break via an appropriate version bump/release note before shipping.

🤖 Prompt for AI Agents
In packages/tanstack-react-start/package.json around lines 84-85, the peer
dependency bump to "^1.132.0" is a breaking change for consumers still on
1.131.x; either relax the range back to a compatible span (for example
">=1.131.49 <2" or another range that includes 1.131.x) to preserve backward
compatibility, or keep the raised floor but mark this as a breaking change by
preparing a major version bump and adding a clear release note/CHANGELOG entry
explaining the incompatibility before shipping.

@wobsoriano wobsoriano changed the title chore(tanstack-react-start): Introduce middleware chore(tanstack-react-start): [do not review] Introduce middleware Sep 26, 2025
@wobsoriano
Copy link
Member Author

!snapshot

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/tanstack-react-start/src/server/utils/index.ts (1)

26-29: Call toAuth on requestState to avoid prototype/enumerability pitfalls.

rest may not retain prototype methods like toAuth. Call requestState.toAuth() directly to prevent runtime errors.

Apply this diff:

-    __clerk_ssr_state: rest.toAuth(),
+    __clerk_ssr_state: requestState.toAuth(),
🧹 Nitpick comments (1)
packages/tanstack-react-start/src/server/clerkMiddleware.ts (1)

37-44: Expose a typed auth helper in context.

Optional: annotate auth to return Clerk’s signed-in/signed-out auth object type to improve DX and reduce any.

Example:

import type { SignedInAuthObject, SignedOutAuthObject } from '@clerk/backend';

type AuthFn = (opts?: PendingSessionOptions) => SignedInAuthObject | SignedOutAuthObject;

// ...
context: {
  clerkInitialState,
  auth: ((opts?: PendingSessionOptions) => requestState.toAuth(opts)) as AuthFn,
},
📜 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 1c717f5 and a0f5987.

📒 Files selected for processing (8)
  • packages/tanstack-react-start/src/client/ClerkProvider.tsx (3 hunks)
  • packages/tanstack-react-start/src/server/clerkMiddleware.ts (1 hunks)
  • packages/tanstack-react-start/src/server/getAuth.ts (2 hunks)
  • packages/tanstack-react-start/src/server/index.ts (1 hunks)
  • packages/tanstack-react-start/src/server/types.ts (2 hunks)
  • packages/tanstack-react-start/src/server/utils/index.ts (1 hunks)
  • packages/tanstack-react-start/src/utils/env.ts (1 hunks)
  • packages/tanstack-react-start/src/utils/errors.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{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/index.ts
  • packages/tanstack-react-start/src/server/clerkMiddleware.ts
  • packages/tanstack-react-start/src/server/types.ts
  • packages/tanstack-react-start/src/utils/errors.ts
  • packages/tanstack-react-start/src/utils/env.ts
  • packages/tanstack-react-start/src/server/utils/index.ts
  • packages/tanstack-react-start/src/server/getAuth.ts
  • packages/tanstack-react-start/src/client/ClerkProvider.tsx
**/*.{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/index.ts
  • packages/tanstack-react-start/src/server/clerkMiddleware.ts
  • packages/tanstack-react-start/src/server/types.ts
  • packages/tanstack-react-start/src/utils/errors.ts
  • packages/tanstack-react-start/src/utils/env.ts
  • packages/tanstack-react-start/src/server/utils/index.ts
  • packages/tanstack-react-start/src/server/getAuth.ts
  • packages/tanstack-react-start/src/client/ClerkProvider.tsx
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/tanstack-react-start/src/server/index.ts
  • packages/tanstack-react-start/src/server/clerkMiddleware.ts
  • packages/tanstack-react-start/src/server/types.ts
  • packages/tanstack-react-start/src/utils/errors.ts
  • packages/tanstack-react-start/src/utils/env.ts
  • packages/tanstack-react-start/src/server/utils/index.ts
  • packages/tanstack-react-start/src/server/getAuth.ts
  • packages/tanstack-react-start/src/client/ClerkProvider.tsx
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/index.ts
  • packages/tanstack-react-start/src/server/clerkMiddleware.ts
  • packages/tanstack-react-start/src/server/types.ts
  • packages/tanstack-react-start/src/utils/errors.ts
  • packages/tanstack-react-start/src/utils/env.ts
  • packages/tanstack-react-start/src/server/utils/index.ts
  • packages/tanstack-react-start/src/server/getAuth.ts
  • packages/tanstack-react-start/src/client/ClerkProvider.tsx
packages/**/index.{js,ts}

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

Use tree-shaking friendly exports

Files:

  • packages/tanstack-react-start/src/server/index.ts
  • packages/tanstack-react-start/src/server/utils/index.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/index.ts
  • packages/tanstack-react-start/src/server/clerkMiddleware.ts
  • packages/tanstack-react-start/src/server/types.ts
  • packages/tanstack-react-start/src/utils/errors.ts
  • packages/tanstack-react-start/src/utils/env.ts
  • packages/tanstack-react-start/src/server/utils/index.ts
  • packages/tanstack-react-start/src/server/getAuth.ts
  • packages/tanstack-react-start/src/client/ClerkProvider.tsx
**/*.{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/index.ts
  • packages/tanstack-react-start/src/server/clerkMiddleware.ts
  • packages/tanstack-react-start/src/server/types.ts
  • packages/tanstack-react-start/src/utils/errors.ts
  • packages/tanstack-react-start/src/utils/env.ts
  • packages/tanstack-react-start/src/server/utils/index.ts
  • packages/tanstack-react-start/src/server/getAuth.ts
  • packages/tanstack-react-start/src/client/ClerkProvider.tsx
**/index.ts

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

Use index.ts files for clean imports but avoid deep barrel exports

Avoid barrel files (index.ts re-exports) as they can cause circular dependencies

Files:

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

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

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/tanstack-react-start/src/client/ClerkProvider.tsx
**/*.tsx

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

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/tanstack-react-start/src/client/ClerkProvider.tsx
🧬 Code graph analysis (4)
packages/tanstack-react-start/src/server/clerkMiddleware.ts (2)
packages/shared/src/netlifyCacheHandler.ts (1)
  • handleNetlifyCacheInDevInstance (43-65)
packages/types/src/session.ts (1)
  • PendingSessionOptions (34-40)
packages/tanstack-react-start/src/utils/env.ts (1)
packages/react-router/src/utils/env.ts (1)
  • getPublicEnvVariables (5-30)
packages/tanstack-react-start/src/server/getAuth.ts (2)
packages/tanstack-react-start/src/utils/index.ts (1)
  • errorThrower (7-9)
packages/tanstack-react-start/src/utils/errors.ts (1)
  • clerkMiddlewareNotConfigured (21-24)
packages/tanstack-react-start/src/client/ClerkProvider.tsx (1)
packages/tanstack-react-start/src/utils/index.ts (1)
  • isClient (3-3)
⏰ 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). (5)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (9)
packages/tanstack-react-start/src/utils/env.ts (1)

4-7: Verify runtime-config env access after removing context parameter.

Dropping the context argument means getPublicEnvVariables now only sees whatever getEnvVariable can pull without the H3 event runtime-config fallback we previously passed through (e.g., event.context.clerkEnv). Please confirm getEnvVariable has been updated to read the new global start context so request-scoped overrides continue to work; otherwise this will regress server-side env lookups.

packages/tanstack-react-start/src/client/ClerkProvider.tsx (2)

23-25: Using global start context for clerkInitialState looks good.

The fallback to {} is reasonable given internal state shape.


30-30: Hydration source selection LGTM.

Server uses middleware-provided state; client uses window.__clerk_init_state.

packages/tanstack-react-start/src/server/types.ts (2)

11-24: New ClerkMiddlewareOptions type looks sound and forward-compatible.

Fields and intersections match Clerk server config expectations.


26-27: Alias preserves prior public name.

LoaderOptions = ClerkMiddlewareOptions keeps existing imports working.

packages/tanstack-react-start/src/server/clerkMiddleware.ts (3)

16-19: Auth request configuration LGTM.

acceptsToken: 'any' is appropriate for mixed cookie/bearer scenarios.


21-31: Handshake redirect flow looks correct; Netlify dev cache handling included.

Redirecting with Clerk-provided headers via throw json(..., { status: 307, headers }) is consistent with react-start middleware patterns.


46-50: Header propagation only occurs on success path; confirm behavior on thrown responses.

If args.next throws a Response (e.g., route guard), these headers won’t be appended. Verify if react-start offers a centralized “onResponse” hook or ensure handlers return NextResult consistently.

Proposed pattern (if supported by the framework):

// Pseudocode
return await args.next({
  context: { ... },
  responseHeaders: requestState.headers,
});

Otherwise, add tests to confirm headers are preserved across error/redirect paths.

packages/tanstack-react-start/src/server/index.ts (1)

3-3: Public export rename is breaking; add a backward-compatible alias or bump major
No internal refs to middlewareHandler found—external consumers may break if renamed. Add

export { clerkMiddleware as middlewareHandler } from './clerkMiddleware'; // TEMP: deprecate and remove in next major

or else bump the major version, and update docs accordingly.

return (
<>
<ScriptOnce>{`window.__clerk_init_state = ${JSON.stringify(routerContext?.clerkInitialState)};`}</ScriptOnce>
<ScriptOnce>{`window.__clerk_init_state = ${JSON.stringify(clerkInitialState)};`}</ScriptOnce>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Escape serialized JSON to avoid XSS/script-breaking sequences.

Embedding raw JSON.stringify into a script can break on </script>, <!--, or U+2028/2029. Safely escape before inlining.

Apply this diff:

-      <ScriptOnce>{`window.__clerk_init_state = ${JSON.stringify(clerkInitialState)};`}</ScriptOnce>
+      <ScriptOnce>{`window.__clerk_init_state = ${safeSerialize(clerkInitialState)};`}</ScriptOnce>

Add this helper near the top of the file (outside the component):

// Safe JSON serializer for embedding into inline <script> tags
const safeSerialize = (data: unknown): string =>
  JSON.stringify(data)
    .replace(/</g, '\\u003c')      // avoid </script
    .replace(/-->/g, '--\\u003e')  // avoid HTML comment close
    .replace(/\u2028/g, '\\u2028') // line sep
    .replace(/\u2029/g, '\\u2029'); // paragraph sep

As per coding guidelines: “Provide meaningful error messages” and “Validate and sanitize outputs.”

🤖 Prompt for AI Agents
In packages/tanstack-react-start/src/client/ClerkProvider.tsx around line 41,
the inline ScriptOnce uses JSON.stringify(clerkInitialState) which can produce
sequences (like </script>, -->, U+2028/U+2029) that break scripts or allow XSS;
add a top-level helper named safeSerialize (outside the component) that returns
a JSON.stringify result with replacements to escape "<", "-->", and
U+2028/U+2029, then replace JSON.stringify(clerkInitialState) with
safeSerialize(clerkInitialState) in the ScriptOnce content to safely embed the
serialized state.

@wobsoriano wobsoriano changed the title chore(tanstack-react-start): [do not review] Introduce middleware chore(tanstack-react-start): Introduce middleware and support for TanStack Start RC Oct 7, 2025

const result = await args.next({
context: {
clerkInitialState,
Copy link
Member Author

Choose a reason for hiding this comment

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

This will be accessed by ClerkProvider as the initial auth state

const result = await args.next({
context: {
clerkInitialState,
auth: (opts?: PendingSessionOptions) => requestState.toAuth(opts),
Copy link
Member Author

Choose a reason for hiding this comment

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

This one is for getAuth()

@wobsoriano wobsoriano requested a review from octoper October 7, 2025 19:29
@wobsoriano wobsoriano changed the title chore(tanstack-react-start): Introduce middleware and support for TanStack Start RC feat(tanstack-react-start): Introduce middleware and support for TanStack Start RC Oct 7, 2025
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 b971abc and b19fa85.

📒 Files selected for processing (2)
  • integration/templates/tanstack-react-start/package.json (2 hunks)
  • integration/templates/tanstack-react-start/vite.config.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • integration/templates/tanstack-react-start/package.json
🧰 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:

  • integration/templates/tanstack-react-start/vite.config.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:

  • integration/templates/tanstack-react-start/vite.config.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:

  • integration/templates/tanstack-react-start/vite.config.ts
integration/**

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

Framework integration templates and E2E tests should be placed under the integration/ directory

Files:

  • integration/templates/tanstack-react-start/vite.config.ts
integration/**/*

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

End-to-end tests and integration templates must be located in the 'integration/' directory.

Files:

  • integration/templates/tanstack-react-start/vite.config.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:

  • integration/templates/tanstack-react-start/vite.config.ts
⏰ 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). (4)
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan

Copy link
Member

@octoper octoper left a comment

Choose a reason for hiding this comment

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

🏖️

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 (1)
packages/tanstack-react-start/src/server/auth.ts (1)

10-11: Consider removing @ts-expect-error with proper typing.

While the @ts-expect-error may be necessary if TanStack's getGlobalStartContext() is genuinely untyped, this suppresses type checking and makes the code harder to maintain. If the start context shape is known, consider defining an interface for it.

If the TanStack Start context has a known shape, apply this approach:

+interface ClerkStartContext {
+  auth?: (opts?: { treatPendingAsSignedOut?: boolean }) => SessionAuthObject | Promise<SessionAuthObject>;
+}
+
 export const auth: GetAuthFnNoRequest<SessionAuthObject, true> = (async (opts?: AuthOptions) => {
-  // @ts-expect-error: Untyped internal Clerk start context
-  const authObjectFn = getGlobalStartContext().auth;
+  const authObjectFn = (getGlobalStartContext() as ClerkStartContext | undefined)?.auth;

   if (!authObjectFn) {

Note: Only apply if the start context structure is documented or stable. If this is truly an internal/unstable API, the current approach may be acceptable.

📜 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 b19fa85 and d5cf00b.

📒 Files selected for processing (5)
  • .changeset/spotty-cooks-march.md (1 hunks)
  • integration/templates/tanstack-react-start/src/routes/__root.tsx (1 hunks)
  • integration/templates/tanstack-react-start/src/routes/user.tsx (1 hunks)
  • packages/tanstack-react-start/src/server/auth.ts (1 hunks)
  • packages/tanstack-react-start/src/server/index.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{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:

  • integration/templates/tanstack-react-start/src/routes/user.tsx
  • packages/tanstack-react-start/src/server/index.ts
  • packages/tanstack-react-start/src/server/auth.ts
  • integration/templates/tanstack-react-start/src/routes/__root.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

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

Use Prettier for consistent code formatting

Files:

  • integration/templates/tanstack-react-start/src/routes/user.tsx
  • packages/tanstack-react-start/src/server/index.ts
  • packages/tanstack-react-start/src/server/auth.ts
  • integration/templates/tanstack-react-start/src/routes/__root.tsx
**/*.{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:

  • integration/templates/tanstack-react-start/src/routes/user.tsx
  • packages/tanstack-react-start/src/server/index.ts
  • packages/tanstack-react-start/src/server/auth.ts
  • integration/templates/tanstack-react-start/src/routes/__root.tsx
**/*.{jsx,tsx}

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

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • integration/templates/tanstack-react-start/src/routes/user.tsx
  • integration/templates/tanstack-react-start/src/routes/__root.tsx
integration/**

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

Framework integration templates and E2E tests should be placed under the integration/ directory

Files:

  • integration/templates/tanstack-react-start/src/routes/user.tsx
  • integration/templates/tanstack-react-start/src/routes/__root.tsx
integration/**/*

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

End-to-end tests and integration templates must be located in the 'integration/' directory.

Files:

  • integration/templates/tanstack-react-start/src/routes/user.tsx
  • integration/templates/tanstack-react-start/src/routes/__root.tsx
**/*.{js,ts,tsx,jsx}

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

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

Files:

  • integration/templates/tanstack-react-start/src/routes/user.tsx
  • packages/tanstack-react-start/src/server/index.ts
  • packages/tanstack-react-start/src/server/auth.ts
  • integration/templates/tanstack-react-start/src/routes/__root.tsx
**/*.tsx

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

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • integration/templates/tanstack-react-start/src/routes/user.tsx
  • integration/templates/tanstack-react-start/src/routes/__root.tsx
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/tanstack-react-start/src/server/index.ts
  • packages/tanstack-react-start/src/server/auth.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/index.ts
  • packages/tanstack-react-start/src/server/auth.ts
packages/**/index.{js,ts}

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

Use tree-shaking friendly exports

Files:

  • packages/tanstack-react-start/src/server/index.ts
**/index.ts

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

Use index.ts files for clean imports but avoid deep barrel exports

Avoid barrel files (index.ts re-exports) as they can cause circular dependencies

Files:

  • packages/tanstack-react-start/src/server/index.ts
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/spotty-cooks-march.md
🧬 Code graph analysis (2)
integration/templates/tanstack-react-start/src/routes/user.tsx (1)
packages/tanstack-react-start/src/server/auth.ts (1)
  • auth (9-21)
packages/tanstack-react-start/src/server/auth.ts (1)
packages/tanstack-react-start/src/utils/errors.ts (1)
  • clerkMiddlewareNotConfigured (21-24)
⏰ 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). (5)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (6)
integration/templates/tanstack-react-start/src/routes/__root.tsx (1)

25-34: Safe to reduce ClerkProvider scope TanStackRouterDevtools and Scripts don’t use Clerk context/hooks, so wrapping only {children} is correct.

packages/tanstack-react-start/src/server/index.ts (1)

1-3: LGTM! Improved export clarity and tree-shaking.

Replacing wildcard re-exports with explicit named exports improves tree-shaking and makes the public API surface clearer.

packages/tanstack-react-start/src/server/auth.ts (2)

17-18: Approve the promise-based flow for future extensibility.

The comment on line 17 correctly notes that keeping this as a promise allows for future asynchronous changes, even though the current implementation may be synchronous.


10-11: Verify getGlobalStartContext() return type and improve typing

  • Confirm that getGlobalStartContext() cannot return undefined (otherwise .auth will throw before the null check).
  • Remove the @ts-expect-error by adding proper TypeScript definitions for the context and its auth property.
integration/templates/tanstack-react-start/src/routes/user.tsx (1)

3-6: LGTM! Clean migration to the new auth API.

The simplified auth() call without requiring a Request object improves the developer experience and aligns with the new middleware-based approach.

.changeset/spotty-cooks-march.md (1)

1-72: LGTM! Comprehensive migration documentation.

The changeset provides clear step-by-step instructions for adopting the new middleware-based approach, including setup for both clerkMiddleware() and <ClerkProvider>, and demonstrates the simplified auth() API usage.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/tanstack-react-start/src/server/types.ts (1)

12-26: Add JSDoc documentation for the public type and new field.

The type definition is structurally sound and the optional organizationSyncOptions field maintains backward compatibility. However, as per coding guidelines, all public APIs must be documented with JSDoc.

Apply this diff to add documentation:

+/**
+ * Options for configuring Clerk middleware in TanStack Start applications.
+ * @public
+ */
 export type ClerkMiddlewareOptions = {
   publishableKey?: string;
   jwtKey?: string;
   secretKey?: string;
   machineSecretKey?: string;
   signInUrl?: string;
   signUpUrl?: string;
+  /**
+   * Options for automatic organization context synchronization based on URL patterns.
+   * Allows middleware to detect organization identifiers in routes and automatically
+   * set the active organization context.
+   * @see {@link https://clerk.com/docs/organizations/overview | Organizations Overview}
+   */
   organizationSyncOptions?: OrganizationSyncOptions;
 } & Pick<VerifyTokenOptions, 'audience' | 'authorizedParties'> &
   MultiDomainAndOrProxy &
   SignInForceRedirectUrl &
   SignInFallbackRedirectUrl &
   SignUpForceRedirectUrl &
   SignUpFallbackRedirectUrl &
   LegacyRedirectProps;

Based on coding guidelines.

🧹 Nitpick comments (1)
packages/tanstack-react-start/src/server/types.ts (1)

28-28: Add deprecation notice to the compatibility alias.

The backward compatibility alias is a good practice. However, it should include a JSDoc deprecation notice to guide users toward the new naming.

Apply this diff:

+/**
+ * @deprecated Use {@link ClerkMiddlewareOptions} instead. This alias is maintained for backward compatibility.
+ */
 export type LoaderOptions = ClerkMiddlewareOptions;

Based on coding guidelines.

📜 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 b2d7f25 and 67e99da.

⛔ Files ignored due to path filters (1)
  • packages/tanstack-react-start/src/__tests__/__snapshots__/exports.test.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (1)
  • packages/tanstack-react-start/src/server/types.ts (3 hunks)
🧰 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/types.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/types.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/tanstack-react-start/src/server/types.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/types.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/types.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/types.ts
🧬 Code graph analysis (1)
packages/tanstack-react-start/src/server/types.ts (1)
packages/backend/src/tokens/types.ts (1)
  • OrganizationSyncOptions (80-110)
⏰ 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). (5)
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan

@@ -1,4 +1,5 @@
import type { VerifyTokenOptions } from '@clerk/backend';
import type { OrganizationSyncOptions } from '@clerk/backend/internal';
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

🧩 Analysis chain

Verify the import path for OrganizationSyncOptions.

Importing from @clerk/backend/internal suggests using a non-public API. Internal APIs can change without notice in minor/patch releases, potentially breaking this integration.

Please verify whether OrganizationSyncOptions is available via a public export path (e.g., @clerk/backend or @clerk/backend/tokens). If it's only available via /internal, confirm this is intentional and document the dependency risk.

Run the following script to check available export paths:


🏁 Script executed:

#!/bin/bash
# Description: Verify OrganizationSyncOptions export paths in @clerk/backend

# Check package.json exports
cat packages/backend/package.json | jq '.exports'

# Search for OrganizationSyncOptions exports
rg -n "export.*OrganizationSyncOptions" packages/backend/

Length of output: 1208


Add JSDoc for renamed type and new field

  • Add JSDoc to ClerkMiddlewareOptions (formerly LoaderOptions) and its organizationSyncOptions field.
  • In the JSDoc, note that OrganizationSyncOptions is imported from @clerk/backend/internal (an “internal” export) and may change without notice.
🤖 Prompt for AI Agents
In packages/tanstack-react-start/src/server/types.ts around line 2, add JSDoc to
the exported ClerkMiddlewareOptions type (previously LoaderOptions) and to its
organizationSyncOptions field explaining that OrganizationSyncOptions is
imported from '@clerk/backend/internal' (an internal export) and may change
without notice; place the JSDoc comment immediately above the type declaration
and above the organizationSyncOptions property, describing the rename and
warning about the internal import volatility.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/tanstack-react-start/src/server/types.ts (1)

12-26: Add JSDoc documentation for the new organizationSyncOptions field.

The new organizationSyncOptions field lacks documentation. While the type itself is documented in the backend package, adding a brief description here would improve discoverability and developer experience, especially since this is a public API type.

As per coding guidelines

Consider adding JSDoc above line 19:

   signInUrl?: string;
   signUpUrl?: string;
+  /**
+   * Options for automatic organization context synchronization based on URL patterns.
+   * Allows the middleware to automatically set the active organization based on URL path parameters.
+   * 
+   * @see {@link OrganizationSyncOptions} for detailed configuration options.
+   */
   organizationSyncOptions?: OrganizationSyncOptions;
 } & Pick<VerifyTokenOptions, 'audience' | 'authorizedParties'> &
🧹 Nitpick comments (2)
packages/tanstack-react-start/src/server/types.ts (2)

28-29: Consider adding a deprecation notice for the LoaderOptions alias.

The type alias maintains backward compatibility, which is good. However, adding a @deprecated JSDoc comment would help guide users toward the new ClerkMiddlewareOptions name, especially if this is part of the migration to the middleware-centric API.

+/**
+ * @deprecated Use {@link ClerkMiddlewareOptions} instead.
+ */
 export type LoaderOptions = ClerkMiddlewareOptions;

2-2: Re-export OrganizationSyncOptions from the public API
OrganizationSyncOptions is only exposed via @clerk/backend/internal; add it to packages/backend/src/index.ts so consumers can import from @clerk/backend instead of an internal path.

📜 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 b2d7f25 and 67e99da.

⛔ Files ignored due to path filters (1)
  • packages/tanstack-react-start/src/__tests__/__snapshots__/exports.test.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (1)
  • packages/tanstack-react-start/src/server/types.ts (3 hunks)
🧰 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/types.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/types.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/tanstack-react-start/src/server/types.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/types.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/types.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/types.ts
🧬 Code graph analysis (1)
packages/tanstack-react-start/src/server/types.ts (1)
packages/backend/src/tokens/types.ts (1)
  • OrganizationSyncOptions (80-110)
⏰ 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). (10)
  • GitHub Check: pr-title-lint
  • GitHub Check: check-major-bump
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Static analysis
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan

@wobsoriano wobsoriano enabled auto-merge (squash) October 9, 2025 20:08
@wobsoriano wobsoriano merged commit 4a1d748 into main Oct 9, 2025
43 checks passed
@wobsoriano wobsoriano deleted the rob/tanstack-rc branch October 9, 2025 20:09
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.

7 participants