fix(clerk): upgrade add-on to @clerk/tanstack-react-start with server middleware #408
main fromrefs/pull/408/head·opened Problem#
The Clerk add-on currently scaffolds @clerk/clerk-react, a client-side-only SDK with no server exports. This makes it incompatible with TanStack Start's primary value proposition — server functions — since any call to Clerk auth on the server fails at runtime with a missing export error.
Solution#
Upgrade the add-on to @clerk/tanstack-react-start, Clerk's official TanStack Start SDK, which provides both client-side components/hooks and server-side exports (auth(), clerkMiddleware()) from a single package. This brings the scaffolded output in line with Clerk's official TanStack Start quickstart.
Changes#
package.json / info.json
- Replaced
@clerk/clerk-reactwith@clerk/tanstack-react-startin bothdependenciesandpackageAdditions - Added
CLERK_SECRET_KEYtoenvVarswithsecret: true— required byclerkMiddleware()for backend token verification
Asset files (provider.tsx, header-user.tsx, demo/clerk.tsx)
- Updated all imports to point to
@clerk/tanstack-react-start - Replaced
<SignedIn>/<SignedOut>with<Show when="signed-in">/<Show when="signed-out">, which is the correct control component API in the new SDK
src/start.ts (new file)
- Scaffolds
createStart()withclerkMiddleware()registered as request middleware, making auth context available to all server functions and enabling route-level protection
_dot_env.local.append
- Appended
CLERK_SECRET_KEY=to the generated.env.localtemplate alongside the existingVITE_CLERK_PUBLISHABLE_KEY
Notes#
@clerk/tanstack-react-startre-exports all client-side hooks and components, so there are no breaking changes for client-side usagecreateStartis imported from@tanstack/react-start, which is already a base dependency — no additional packages introduced- The
tanstackStart()Vite plugin auto-discoverssrc/start.tsby convention; no changes tovite.config.tsare required
Summary by CodeRabbit#
New Features
- Added TanStack React Start integration for Clerk and wired Clerk into the app startup flow.
- Authentication UI updated to use TanStack-compatible Clerk components.
Chores
- Updated Clerk integration dependency to the TanStack-compatible package.
- Added required CLERK_SECRET_KEY environment variable (secret) to configuration.
- 1
📝 Walkthrough
Walkthrough#
This PR migrates Clerk usage to the TanStack React Start integration: updates imports and dependency, replaces SignedIn/SignedOut patterns with Show predicates, adds a start.ts wiring clerkMiddleware into Start, and adds CLERK_SECRET_KEY to env metadata and template.
Changes#
Clerk TanStack Start migration
Layer / File(s) Summary Env / Metadata
packages/create/src/frameworks/react/add-ons/clerk/info.json,packages/create/src/frameworks/react/add-ons/clerk/assets/_dot_env.local.appendAdds CLERK_SECRET_KEYentry to addon metadata and appendsCLERK_SECRET_KEY=to the local env template.Dependency
packages/create/src/frameworks/react/add-ons/clerk/package.jsonReplaces dependency @clerk/clerk-reactwith@clerk/tanstack-react-start.Start wiring / Middleware
packages/create/src/frameworks/react/add-ons/clerk/assets/src/start.tsNew file exporting startInstancethat registersclerkMiddleware()as request middleware for TanStack React Start.Provider import
packages/create/src/frameworks/react/add-ons/clerk/assets/src/integrations/clerk/provider.tsxChanges ClerkProviderimport source from@clerk/clerk-reactto@clerk/tanstack-react-start(usage unchanged).Component imports / usage
packages/create/src/frameworks/react/add-ons/clerk/assets/src/integrations/clerk/header-user.tsx,.../routes/demo/clerk.tsxSwitches relevant imports (e.g., useUser,SignedIn/SignedOutreplacements) to@clerk/tanstack-react-startand migrates conditional rendering toShowwithwhen="signed-in"/when="signed-out"where applied.Sequence Diagram#
sequenceDiagram participant Browser as Browser (UI) participant Start as TanStack React Start participant Clerk as Clerk Middleware/Service Browser->>Start: HTTP request / user action Start->>Clerk: clerkMiddleware() verifies session (uses CLERK_SECRET_KEY) Clerk-->>Start: auth result (session/user) Start-->>Browser: renders components (HeaderUser uses Show when="signed-in"/"signed-out") Browser->>Clerk: client-side calls (SignIn/SignOut/UserButton) via TanStack client bindings Clerk-->>Browser: client auth state updatesEstimated code review effort#
🎯 3 (Moderate) | ⏱️ ~20 minutes
Poem#
🐰 I hopped from React to TanStack's start, Wove middleware threads and played my part, A secret key tucked in the burrow deep, Show when signed-in, show when asleep, Hooray — auth hops forward, light and fleet!
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
Check name Status Explanation Resolution Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold. ✏️ Tip: You can configure your own custom pre-merge checks in the settings.✅ Passed checks (4 passed)
Check name Status Explanation Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled. Title check ✅ Passed The title accurately summarizes the main change: upgrading the Clerk add-on from @clerk/clerk-reactto@clerk/tanstack-react-startand adding server middleware support.Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request. Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request. ✨ Finishing Touches
🧪 Generate unit tests (beta)
- Create PR with unit tests
Tip
💬 Introducing Slack Agent: The best way for teams to turn conversations into code.
Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
- Generate code and open pull requests
- Plan features and break down work
- Investigate incidents and troubleshoot customer tickets together
- Automate recurring tasks and respond to alerts with triggers
- Summarize progress and report instantly
Built for teams:
- Shared memory across your entire org—no repeating context
- Per-thread sandboxes to safely plan and execute work
- Governance built-in—scoped access, auditability, and budget controls
One agent for your entire SDLC. Right inside Slack.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds. Comment `@coderabbitai help` to get the list of available commands and usage tips.Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/create/src/frameworks/react/add-ons/clerk/assets/src/routes/demo/clerk.tsx (1)
1-8: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick winuseUseris imported twice — this is a compile-breaking duplicate identifier, and@clerk/clerk-reactwas never fully removed.Line 1 adds the new
useUserimport from@clerk/tanstack-react-start, but the old@clerk/clerk-reactimport block (lines 3–8) was never removed. This leavesuseUserdeclared twice, which TypeScript will reject as a duplicate identifier.SignIn,SignedIn, andSignedOutare also still sourced from the old package, keeping the dependency that the PR intends to remove.@clerk/tanstack-react-startre-exportsSignedIn,SignedOut,SignIn, anduseUser, so the entire old import block can be replaced.Additionally,
@clerk/tanstack-react-startis currently in beta — worth noting for production scaffolding decisions.🐛 Proposed fix — consolidate into a single import from the new package
-import { useUser } from '@clerk/tanstack-react-start' -import { createFileRoute } from '@tanstack/react-router' -import { - SignIn, - SignedIn, - SignedOut, - useUser, -} from '@clerk/clerk-react' +import { + SignIn, + SignedIn, + SignedOut, + useUser, +} from '@clerk/tanstack-react-start' +import { createFileRoute } from '@tanstack/react-router'🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/create/src/frameworks/react/add-ons/clerk/assets/src/routes/demo/clerk.tsx` around lines 1 - 8, You have a duplicate import of useUser and leftover imports from `@clerk/clerk-react`; remove the entire import block that pulls SignIn, SignedIn, SignedOut, and useUser from '@clerk/clerk-react' and consolidate them into the single new import from '@clerk/tanstack-react-start' (so import useUser, SignIn, SignedIn, SignedOut together alongside any existing imports like createFileRoute), ensuring only one useUser symbol is imported and the old package reference is deleted.🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed. Outside diff comments: In `@packages/create/src/frameworks/react/add-ons/clerk/assets/src/routes/demo/clerk.tsx`: - Around line 1-8: You have a duplicate import of useUser and leftover imports from `@clerk/clerk-react`; remove the entire import block that pulls SignIn, SignedIn, SignedOut, and useUser from '@clerk/clerk-react' and consolidate them into the single new import from '@clerk/tanstack-react-start' (so import useUser, SignIn, SignedIn, SignedOut together alongside any existing imports like createFileRoute), ensuring only one useUser symbol is imported and the old package reference is deleted.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
eb3ff097-3151-4815-b1e0-80ed77ff12a4📥 Commits
Reviewing files that changed from the base of the PR and between d9b7f09dd675a75c3bf34a0aec708759cca07a34 and f6eec03eac78fcaef2be6a6816766137b34b7485.
📒 Files selected for processing (2)
packages/create/src/frameworks/react/add-ons/clerk/assets/src/routes/demo/clerk.tsxpackages/create/src/frameworks/react/add-ons/clerk/info.json
✅ Files skipped from review due to trivial changes (1)
- packages/create/src/frameworks/react/add-ons/clerk/info.json
Review the following changes in direct dependencies. Learn more about Socket for GitHub.
Diff Package Supply Chain
SecurityVulnerability Quality Maintenance License @clerk/tanstack-react-start@1.2.7 Warning
Review the following alerts detected in dependencies.
According to your organization's Security Policy, it is recommended to resolve "Warn" alerts. Learn more about Socket for GitHub.
Action Severity Alert (click "▶" to expand/collapse) Warn Obfuscated code: npm
@clerk/reactis 90.0% likely obfuscatedConfidence: 0.90
Location: Package overview
From:
?→npm/@clerk/tanstack-react-start@1.2.7→npm/@clerk/react@6.6.6ℹ Read more on: This package | This alert | What is obfuscated code?
Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at
support@socket.dev.Suggestion: Packages should not obfuscate their code. Consider not using packages with obfuscated code.
Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment
@SocketSecurity ignore npm/@clerk/react@6.6.6. You can also ignore all packages with@SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.Thanks for putting this together and calling out the missing server auth support. The migration shipped through #490, so I'm closing this as superseded.
The published CLI 0.72.16 generates Clerk's TanStack Start SDK, registers
clerkMiddleware()alongside the CSRF middleware, and adds a placeholder forCLERK_SECRET_KEY. If you still hit a gap with server auth in a fresh scaffold, please share the smallest case that shows it.tannerlinsley closed this
Sign in to join this conversation.
⚠️ No Changeset found#
Latest commit: d9b7f09dd675a75c3bf34a0aec708759cca07a34
Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.
This PR includes no changesets
When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types
Click here to learn what changesets are, and how to add one.
Click here if you're a maintainer who wants to add a changeset to this PR