-
Notifications
You must be signed in to change notification settings - Fork 391
feat(tanstack-react-start): Introduce middleware and support for TanStack Start RC #6859
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
🦋 Changeset detectedLatest commit: b19fa85 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughAdds a Clerk per-request middleware for TanStack Start, moves server/client Clerk wiring to use the global start context, updates types/errors/utilities and integration templates, bumps TanStack package versions to 1.132.x, adjusts CI matrix, and adds a changeset. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor U as User
participant B as Browser
participant S as Start App
participant M as clerkMiddleware
participant C as Clerk Backend
participant R as Router/Loaders
U->>B: Navigate / Request
B->>S: HTTP request
S->>M: run request middleware
M->>C: authenticateRequest(request, { allowAnyToken: true })
C-->>M: auth state + headers (or redirect Location)
alt Netlify dev cache handshake
M-->>B: 307 Redirect + Clerk headers
else Normal request
M->>S: next({ context: { clerkInitialState, auth } })
S->>R: handle routing/loaders with enriched context
R-->>S: Response
S-->>B: Response + Clerk headers
end
sequenceDiagram
autonumber
participant Client as Client App
participant G as Global Start Context
Client->>G: getGlobalStartContext()
G-->>Client: { clerkInitialState }
Client->>Client: ScriptOnce serializes clerkInitialState -> window.__clerk_init_state
note right of Client: fallback to existing window state only if present
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this 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.
⛔ 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)
"@tanstack/react-router": "^1.132.0", | ||
"@tanstack/react-start": "^1.132.0", |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
!snapshot |
There was a problem hiding this 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
: CalltoAuth
onrequestState
to avoid prototype/enumerability pitfalls.
rest
may not retain prototype methods liketoAuth
. CallrequestState.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 typedauth
helper in context.Optional: annotate
auth
to return Clerk’s signed-in/signed-out auth object type to improve DX and reduceany
.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.
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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 meansgetPublicEnvVariables
now only sees whatevergetEnvVariable
can pull without the H3 event runtime-config fallback we previously passed through (e.g.,event.context.clerkEnv
). Please confirmgetEnvVariable
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 forclerkInitialState
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
: NewClerkMiddlewareOptions
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 returnNextResult
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 tomiddlewareHandler
found—external consumers may break if renamed. Addexport { clerkMiddleware as middlewareHandler } from './clerkMiddleware'; // TEMP: deprecate and remove in next majoror 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> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
There was a problem hiding this 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.
📒 Files selected for processing (1)
.github/workflows/ci.yml
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
.github/workflows/*.yml
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
CI/CD must be configured with GitHub Actions.
Files:
.github/workflows/ci.yml
⏰ 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). (29)
- GitHub Check: Integration Tests (tanstack-react-start, chrome)
- GitHub Check: Integration Tests (react-router, chrome)
- GitHub Check: Integration Tests (nextjs, chrome, 14)
- GitHub Check: Integration Tests (machine, chrome)
- GitHub Check: Integration Tests (astro, chrome)
- GitHub Check: Integration Tests (custom, chrome)
- GitHub Check: Integration Tests (nextjs, chrome, 15)
- GitHub Check: Integration Tests (vue, chrome)
- GitHub Check: Integration Tests (sessions:staging, chrome)
- GitHub Check: Integration Tests (handshake, chrome)
- GitHub Check: Integration Tests (nuxt, chrome)
- GitHub Check: Integration Tests (express, chrome)
- GitHub Check: Integration Tests (handshake:staging, chrome)
- GitHub Check: Integration Tests (sessions, chrome)
- GitHub Check: Integration Tests (billing, chrome)
- GitHub Check: Integration Tests (expo-web, chrome)
- GitHub Check: Integration Tests (elements, chrome)
- GitHub Check: Integration Tests (localhost, chrome)
- GitHub Check: Integration Tests (ap-flows, chrome)
- GitHub Check: Integration Tests (generic, chrome)
- GitHub Check: Integration Tests (quickstart, chrome)
- GitHub Check: Publish with pkg-pr-new
- GitHub Check: Unit Tests (22, **)
- GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
- GitHub Check: Static analysis
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
There was a problem hiding this 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.
📒 Files selected for processing (2)
integration/presets/utils.ts
(1 hunks)integration/templates/tanstack-react-start/package.json
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{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/package.json
integration/presets/utils.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/package.json
integration/presets/utils.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/package.json
integration/presets/utils.ts
**/*.{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/presets/utils.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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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/presets/utils.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/presets/utils.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). (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 (1)
integration/presets/utils.ts (1)
1-8
: Verify unusedpkg
parameter impact
Ensure no callers rely on package-specific behavior; if safe, remove thepkg
parameter, prefix it with_
, or add a JSDoc explaining why it remains.
I'm having some trouble installing the preview build $ bun add https://pkg.pr.new/@clerk/tanstack-react-start@6859
[0.82ms] ".env.local", ".env"
bun add v1.2.23 (cf136713)
error: Package "@clerk/tanstack-react-start@https://pkg.pr.new/@clerk/tanstack-react-start@6859" has a dependency loop
Resolution: "@clerk/[email protected]"
Dependency: "@clerk/tanstack-react-start@https://pkg.pr.new/@clerk/tanstack-react-start@6859"
error: An internal error occurred (DependencyLoop) |
There was a problem hiding this 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
♻️ Duplicate comments (1)
packages/tanstack-react-start/src/server/getAuth.ts (1)
8-12
: Guard the Start context before accessing.auth
.
getGlobalStartContext()
can beundefined
until the middleware wires it up. Dereferencing.auth
directly will throw and bypassclerkMiddlewareNotConfigured
, reintroducing the crash we flagged earlier. Please capture the context, guard it, and only call.auth
when available so the intended error surfaces instead of a runtime exception.- // @ts-expect-error: Untyped internal Clerk start context - const authObjectFn = getGlobalStartContext().auth; - - if (!authObjectFn) { + const startContext = getGlobalStartContext() as + | { auth?: (opts?: PendingSessionOptions) => unknown } + | undefined; + const authObjectFn = startContext?.auth; + + if (!authObjectFn) { return errorThrower.throw(clerkMiddlewareNotConfigured); }
📜 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.
📒 Files selected for processing (1)
packages/tanstack-react-start/src/server/getAuth.ts
(1 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/getAuth.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/getAuth.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/tanstack-react-start/src/server/getAuth.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/getAuth.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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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/getAuth.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/getAuth.ts
🧬 Code graph analysis (1)
packages/tanstack-react-start/src/server/getAuth.ts (4)
packages/backend/src/internal.ts (2)
GetAuthFnNoRequest
(17-17)AuthOptions
(16-16)packages/backend/src/tokens/types.ts (2)
GetAuthFnNoRequest
(244-284)AuthOptions
(190-190)packages/tanstack-react-start/src/utils/index.ts (1)
errorThrower
(7-9)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). (6)
- GitHub Check: Build Packages
- 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
There was a problem hiding this 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
♻️ Duplicate comments (1)
packages/tanstack-react-start/src/server/getAuth.ts (1)
10-15
:⚠️ Critical: Prevent runtime crash when start context is missingThis issue was flagged in a previous review and remains unresolved. Directly accessing
getGlobalStartContext().auth
will throwCannot read properties of undefined
when the middleware isn't configured or the context is missing. This bypasses the intendedclerkMiddlewareNotConfigured
error and crashes the application instead of providing a helpful error message.Apply this diff to guard the access:
- // @ts-expect-error: Untyped internal Clerk start context - const authObjectFn = getGlobalStartContext().auth; + const startContext = getGlobalStartContext() as + | { auth?: (opts?: PendingSessionOptions) => unknown } + | undefined; + const authObjectFn = startContext?.auth;
🧹 Nitpick comments (1)
packages/tanstack-react-start/src/server/getAuth.ts (1)
17-18
: Clarify or remove redundant commentThe comment "We're keeping it a promise for now for future changes" doesn't add much value since the function signature already requires returning a promise (
GetAuthFnNoRequest<SessionAuthObject, true>
wheretrue
meansReturnsPromise = true
). Consider either removing this comment or clarifying what specific future changes are anticipated.
📜 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.
📒 Files selected for processing (3)
.changeset/spotty-cooks-march.md
(1 hunks)integration/templates/tanstack-react-start/src/routes/user.tsx
(1 hunks)packages/tanstack-react-start/src/server/getAuth.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- integration/templates/tanstack-react-start/src/routes/user.tsx
🧰 Additional context used
📓 Path-based instructions (7)
.changeset/**
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Automated releases must use Changesets.
Files:
.changeset/spotty-cooks-march.md
**/*.{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/getAuth.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/getAuth.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/tanstack-react-start/src/server/getAuth.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/getAuth.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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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/getAuth.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/getAuth.ts
🧬 Code graph analysis (1)
packages/tanstack-react-start/src/server/getAuth.ts (6)
packages/express/src/getAuth.ts (1)
getAuth
(15-23)packages/fastify/src/getAuth.ts (1)
getAuth
(7-15)packages/backend/src/tokens/types.ts (3)
GetAuthFnNoRequest
(244-284)SessionAuthObject
(185-185)AuthOptions
(190-190)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/backend/src/tokens/authObjects.ts (1)
getAuthObjectForAcceptedToken
(462-492)
⏰ 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: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
.changeset/spotty-cooks-march.md (1)
1-70
: Documentation looks clear and comprehensiveThe changeset effectively documents the migration to the new middleware approach with three practical examples. The usage instructions are clear and align with the code changes in this PR.
// @ts-expect-error: Untyped internal Clerk start context | ||
const authObjectFn = getGlobalStartContext().auth; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion | 🟠 Major
Replace @ts-expect-error
with proper typing
Suppressing type errors with @ts-expect-error
hides potential type mismatches and makes the code harder to maintain. The comment indicates the start context is untyped, but the fix suggested above provides explicit typing that documents the expected shape.
This refactor is included in the diff above (lines 10-15).
🤖 Prompt for AI Agents
In packages/tanstack-react-start/src/server/getAuth.ts around lines 10-11,
remove the line using // @ts-expect-error and instead introduce a proper type
for the start context (e.g. an interface/type with the auth property and its
expected signature), then replace the suppressor by typing/casting the result of
getGlobalStartContext() to that type and assigning auth from it; add any
necessary imports/exports for the type so the shape is documented and TypeScript
can validate the auth property rather than suppressing the error.
|
||
const result = await args.next({ | ||
context: { | ||
clerkInitialState, |
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
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()
There was a problem hiding this 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.
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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
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:
Setup
Create a
src/start.ts
file and addclerkMiddleware()
to the list of request middlewares:Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
New Features
Dependency Updates
Refactor
Chores