Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/elements/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
},
"devDependencies": {
"@statelyai/inspect": "^0.4.0",
"@tanstack/react-router": "1.131.49",
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Add TanStack Router as an optional peer dependency for consistency.

The package follows a pattern where framework-specific integrations (like Next.js) are listed as both devDependencies (for testing) and optional peerDependencies (for proper resolution in user projects). TanStack Router should follow the same pattern to ensure users can manage their own version while @clerk/elements adapts to it.

Apply this diff to add TanStack Router as an optional peer dependency:

   "peerDependencies": {
+    "@tanstack/react-router": "^1.0.0",
     "next": "^13.5.4 || ^14.0.3 || ^15",
     "react": "catalog:peer-react",
     "react-dom": "catalog:peer-react"
   },
   "peerDependenciesMeta": {
+    "@tanstack/react-router": {
+      "optional": true
+    },
     "next": {
       "optional": true
     }
   },
🤖 Prompt for AI Agents
In packages/elements/package.json around line 89, add "@tanstack/react-router":
"1.131.49" to the optionalPeerDependencies object (create the
optionalPeerDependencies section if it doesn't exist) so TanStack Router is
listed as an optional peer dependency for consumers; also ensure the same
version is present in devDependencies (add it there if missing) so tests/builds
use the pinned version.

"concurrently": "^9.2.1",
"next": "14.2.33"
},
Expand Down
48 changes: 48 additions & 0 deletions packages/elements/src/react/router/tanstack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import type { ClerkHostRouter } from '@clerk/types';
import { useRouter } from '@tanstack/react-router';

import { usePathnameWithoutCatchAll } from '../utils/path-inference/tanstack';

/**
* Clerk Elements router integration hook for TanStack Router.
*
* Provides a standardized router interface (`ClerkHostRouter`) that Clerk Elements
* can use to navigate and read URL state within a TanStack Router application.
*
* @returns A `ClerkHostRouter` object with navigation methods (`push`, `replace`, `shallowPush`),
* URL state accessors (`pathname`, `searchParams`), and path inference (`inferredBasePath`).
*
* @example
* ```tsx
* import { useTanStackRouter } from '@clerk/elements/tanstack';
*
* function MyComponent() {
* const router = useTanStackRouter();
* // Clerk Elements will use this router for navigation
* }
* ```
*
* @remarks
* - Requires TanStack Router v1.x+ to be installed and configured in your application.
* - The hook must be called within a TanStack Router context (inside a `<RouterProvider>`).
*/
export const useTanStackRouter = (): ClerkHostRouter => {
const router = useRouter();
const pathname = router.location.pathname;
const searchString = router.location.search;
const inferredBasePath = usePathnameWithoutCatchAll(); //
const getSearchParams = () => new URLSearchParams(searchString);

return {
mode: 'path',
name: 'TanStackRouter',
push: (path: string) => router.navigate({ to: path }),
replace: (path: string) => router.navigate({ to: path, replace: true }),
shallowPush: (path: string) =>
// In TanStack Router, all navigations are already shallow by default.
router.navigate({ to: path }),
pathname: () => pathname,
searchParams: () => getSearchParams(),
inferredBasePath: () => inferredBasePath,
};
};
40 changes: 40 additions & 0 deletions packages/elements/src/react/utils/path-inference/tanstack.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { useParams, useRouter } from '@tanstack/react-router';
import React from 'react';

import { removeOptionalCatchAllSegment } from './utils';

/**
* This hook grabs the current pathname and removes any (optional) catch-all segments.
* Adapted from Next.js App Router logic for TanStack Router.
* @example
* Route: /user/$[id]/profile/$[...rest] (or file: user.[id].profile.[[...rest]].tsx)
* Pathname: /user/123/profile/security
* Params: { id: '123', rest: ['security'] }
* Returns: /user/123/profile
* @returns The pathname without any catch-all segments
*/
export const usePathnameWithoutCatchAll = (): string => {
const router = useRouter();

const pathname = router?.location.pathname || '';
const params = useParams() as Record<string, string | string[] | undefined>;

return React.useMemo(() => {
const processedPath = removeOptionalCatchAllSegment(pathname);
const pathParts = processedPath.split('/').filter(Boolean);
const catchAllParams = Object.values(params || {})
.filter((v): v is string[] => Array.isArray(v))
.flat(Infinity);

if (!pathname || catchAllParams.length === 0) {
return pathname.replace(/\/$/, '') || '/';
}

// Slice off the trailing segments matching the catch-all length
// E.g., pathParts = ['user', '123', 'profile', 'security'], length=1 → slice(0, 3) = /user/123/profile
const baseParts = pathParts.slice(0, pathParts.length - catchAllParams.length);
const basePath = `/${baseParts.join('/')}`;

return basePath.replace(/\/$/, '') || '/';
}, [pathname, params]);
};
Loading