### Install Auth0 SDK Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Install the Auth0 React SDK using npm. This is the first step to integrate Auth0 authentication. ```bash npm install @auth0/auth0-react ``` -------------------------------- ### Verify package installation Source: https://tanstack.com/router/latest/docs/quick-start.md Check the dependencies section of your package.json to confirm the router is installed. ```json { "dependencies": { "@tanstack/react-router": "^x.x.x" } } ``` ```json { "dependencies": { "@tanstack/solid-router": "^x.x.x" } } ``` -------------------------------- ### Install Supabase Client Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Installs the Supabase JavaScript client library using npm. This is the first step to integrating Supabase services. ```bash npm install @supabase/supabase-js ``` -------------------------------- ### Start/Full-Stack Applications - Solid Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md Example of rendering `` in a Solid full-stack application. ```APIDOC ## Start/Full-Stack Applications - Solid ### Description Example of rendering `` in a Solid full-stack application. ### Method N/A (Component Integration) ### Endpoint N/A (Component Integration) ### Request Example ```tsx import { HeadContent } from '@tanstack/solid-router' export const Route = createRootRoute({ component: () => ( ), }) ``` ### Response N/A (Component Integration) ``` -------------------------------- ### Install Clerk SDK Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Install the Clerk React SDK using npm. This is required for Clerk integration. ```bash npm install @clerk/clerk-react ``` -------------------------------- ### Menu Component Usage Example Source: https://tanstack.com/router/latest/docs/guide/type-utilities.md Example of how to use the Menu component with relative navigation options. ```tsx ``` -------------------------------- ### Start/Full-Stack Applications - React Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md Example of rendering `` in a React full-stack application. ```APIDOC ## Start/Full-Stack Applications - React ### Description Example of rendering `` in a React full-stack application. ### Method N/A (Component Integration) ### Endpoint N/A (Component Integration) ### Request Example ```tsx import { HeadContent } from '@tanstack/react-router' export const Route = createRootRoute({ component: () => ( ), }) ``` ### Response N/A (Component Integration) ``` -------------------------------- ### Install vibe-rules Globally Source: https://tanstack.com/router/latest/docs/llm-support.md Install `vibe-rules` globally using pnpm. This command is used to set up the LLM assistance rules for TanStack Router. ```bash pnpm add -g vibe-rules ``` -------------------------------- ### Install vibe-rules for Cursor Source: https://tanstack.com/router/latest/docs/llm-support.md Integrate `vibe-rules` with the Cursor editor. This command enables context-aware help within Cursor. ```bash vibe-rules install cursor ``` -------------------------------- ### createLink Basic Example (Solid) Source: https://tanstack.com/router/latest/docs/guide/custom-link.md Demonstrates how to create a custom Link component in Solid.js using `createLink`, enabling custom styling and behavior with type safety. ```APIDOC ## createLink Basic Example (Solid) ### Description This example illustrates creating a custom `Link` component in Solid.js using `createLink`. It allows for custom props and styles while maintaining type safety provided by TanStack Router. ### Method N/A (This is a component creation example) ### Endpoint N/A ### Parameters N/A ### Request Example ```tsx import * as Solid from 'solid-js'; import { createLink, LinkComponent } from '@tanstack/solid-router'; export const Route = createRootRoute({ component: RootComponent, }); type BasicLinkProps = Solid.JSX.IntrinsicElements['a'] & { // Add any additional props you want to pass to the anchor element } const BasicLinkComponent: Solid.Component = (props) => ( {props.children} ) const CreatedLinkComponent = createLink(BasicLinkComponent) export const CustomLink: LinkComponent = (props) => { return } ``` ### Response N/A (This is a component creation example) ``` -------------------------------- ### fetchOrRedirect Usage Example Source: https://tanstack.com/router/latest/docs/guide/type-utilities.md Example demonstrating the type-safe usage of the fetchOrRedirect function with a redirect option. ```tsx fetchOrRedirect('http://example.com/', { to: '/login' }) ``` -------------------------------- ### Single-Page Applications - Solid Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md Example of rendering `` in a Solid single-page application. ```APIDOC ## Single-Page Applications - Solid ### Description Example of rendering `` in a Solid single-page application. Ensure the `` tag is removed from `index.html` if present. ### Method N/A (Component Integration) ### Endpoint N/A (Component Integration) ### Request Example ```tsx import { HeadContent } from '@tanstack/solid-router' const rootRoute = createRootRoute({ component: () => ( <> <HeadContent /> <Outlet /> </> ), }) ``` ### Response N/A (Component Integration) ``` -------------------------------- ### Install TanStack Router CLI Source: https://tanstack.com/router/latest/docs/installation/with-router-cli.md Install the TanStack Router CLI as a development dependency for your project. ```bash npm install @tanstack/router-cli --save-dev ``` ```bash yarn add @tanstack/router-cli --dev ``` ```bash pnpm add @tanstack/router-cli --save-dev ``` -------------------------------- ### Install TanStack Router Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-router.md Install the TanStack Router package using npm. Refer to the detailed installation guide for more information. ```bash npm i @tanstack/react-router ``` -------------------------------- ### createLink Basic Example (React) Source: https://tanstack.com/router/latest/docs/guide/custom-link.md Demonstrates how to create a basic custom Link component in React using `createLink` for custom styling and behavior while maintaining type safety. ```APIDOC ## createLink Basic Example (React) ### Description This example shows how to create a custom `Link` component in React using `createLink`. It allows for adding custom props and styles while preserving the type safety of TanStack Router. ### Method N/A (This is a component creation example) ### Endpoint N/A ### Parameters N/A ### Request Example ```tsx import * as React from 'react'; import { createLink, LinkComponent } from '@tanstack/react-router'; interface BasicLinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> { // Add any additional props you want to pass to the anchor element } const BasicLinkComponent = React.forwardRef<HTMLAnchorElement, BasicLinkProps>( (props, ref) => { return ( <a ref={ref} {...props} className={'block px-3 py-2 text-blue-700'} /> ); }, ); const CreatedLinkComponent = createLink(BasicLinkComponent); export const CustomLink: LinkComponent<typeof BasicLinkComponent> = (props) => { return <CreatedLinkComponent preload={'intent'} {...props} />; } ``` ### Response N/A (This is a component creation example) ### Usage Example ```tsx <CustomLink to={'/dashboard/invoices/$invoiceId'} params={{ invoiceId: 0 }} /> ``` ``` -------------------------------- ### Recommended Flat Config Setup for ESLint Source: https://tanstack.com/router/latest/docs/eslint/eslint-plugin-router.md Configure ESLint using the flat config format to enable all recommended rules provided by the TanStack Router ESLint plugin. This setup assumes ESLint 9.0 or later. ```javascript import pluginRouter from '@tanstack/eslint-plugin-router' export default [ ...pluginRouter.configs['flat/recommended'], // Any other config... ] ``` -------------------------------- ### Define a File-Based Route with createFileRoute Source: https://tanstack.com/router/latest/docs/api/router/createFileRouteFunction.md This example demonstrates how to initialize a route using createFileRoute. It includes a loader function and a component that consumes the loader data via the useLoaderData hook. ```tsx import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/')({ loader: () => { return 'Hello World' }, component: IndexComponent, }) function IndexComponent() { const data = Route.useLoaderData() return <div>{data}</div> } ``` -------------------------------- ### Usage of useConditionalNavigate Source: https://tanstack.com/router/latest/docs/guide/type-utilities.md Example of initializing the hook with type-safe navigation options. ```tsx const { enable, disable, navigate } = useConditionalNavigate({ to: '/posts/$postId', params: { postId: 'postId' }, }) ``` -------------------------------- ### Using Mutation Keys for State Reset Source: https://tanstack.com/router/latest/docs/guide/data-mutations.md This example demonstrates how to use a keying mechanism with mutations to automatically reset their state when relevant parameters (like roomId) change. ```APIDOC ## Using Mutation Keys ### Description This section illustrates how to leverage a keying mechanism provided by a mutation library to reset mutation state when a key changes. This is particularly useful for clearing submission and loading states related to specific data or routes. ### Method Not applicable (Client-side logic) ### Endpoint Not applicable (Client-side logic) ### Parameters Not applicable ### Request Example ```tsx const routeApi = getRouteApi('/room/$roomId/chat') function ChatRoom() { const { roomId } = routeApi.useParams() const sendMessageMutation = useCoolMutation({ fn: sendMessage, // Clear the mutation state when the roomId changes // including any submission state key: ['sendMessage', roomId], }) // Fire off a bunch of messages const test = () => { sendMessageMutation.mutate({ roomId, message: 'Hello!' }) sendMessageMutation.mutate({ roomId, message: 'How are you?' }) sendMessageMutation.mutate({ roomId, message: 'Goodbye!' }) } return ( <> {sendMessageMutation.submissions.map((submission) => ( <div key={submission.id}> <div>{submission.status}</div> <div>{submission.message}</div> </div> ))} </> ) } ``` ### Response Not applicable (Client-side logic) ``` -------------------------------- ### Example Component Tree Rendering Source: https://tanstack.com/router/latest/docs/routing/route-trees.md Demonstrates the component hierarchy rendered by TanStack Router based on a nested route structure. ```tsx <Blog> <Posts> <Post postId="123" /> </Posts> </Blog> ``` -------------------------------- ### Programmatic Navigation with useNavigate Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Programmatic navigation using `navigate()` respects output rewrites. This example demonstrates navigating to '/about', which will be displayed as '/en/about' in the browser due to rewrites. ```tsx const navigate = useNavigate() // Navigates to /about internally, displays /en/about in browser navigate({ to: '/about' }) ``` -------------------------------- ### Initialize Root Route and Router Source: https://tanstack.com/router/latest/docs/api/router/createRootRouteFunction.md This example demonstrates how to create a root route using createRootRoute, define a component for the root outlet, and integrate it into a router instance. It shows the standard pattern for building a route tree by adding children to the root route. ```tsx import { createRootRoute, createRouter, Outlet } from '@tanstack/react-router'; const rootRoute = createRootRoute({ component: () => <Outlet />, }); const routeTree = rootRoute.addChildren([ // ... other routes ]); const router = createRouter({ routeTree, }); ``` -------------------------------- ### Link Component Active State Examples Source: https://tanstack.com/router/latest/docs/guide/navigation.md Demonstrates various scenarios of Link component usage and how their active states are determined based on the current route and provided options. ```tsx const link1 = ( <Link to="/blog/post/$postId" params={{ postId: 'my-first-blog-post' }}> Blog Post </Link> ) const link2 = <Link to="/blog/post">Blog Post</Link> const link3 = <Link to="/blog">Blog Post</Link> ``` ```tsx const link4 = ( <Link to="/blog/post/$postId" params={{ postId: 'my-second-blog-post' }}> Blog Post </Link> ) ``` ```tsx const link = ( <Link to="/" activeOptions={{ exact: true }}> Home </Link> ) ``` -------------------------------- ### Server-side Considerations: Server Middleware Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Explains how URL rewrites are applied on the server when using TanStack Start, specifically how they are handled during request parsing. ```APIDOC ## Server-side Considerations URL rewrites apply on both client and server. When using TanStack Start: ### Server Middleware Rewrites are applied when parsing incoming requests: ### Request Example ```tsx // router.tsx export const router = createRouter({ routeTree, rewrite: { input: ({ url }) => deLocalizeUrl(url), output: ({ url }) => localizeUrl(url), }, }) ``` The server handler will use the same rewrite configuration to parse incoming URLs and generate responses with the correct external URLs. ``` -------------------------------- ### Create and Configure NotFoundRoute in React Source: https://tanstack.com/router/latest/docs/api/router/NotFoundRouteClass.md This example demonstrates how to create a NotFoundRoute instance and configure it with a custom component. It then integrates this into the TanStack Router setup. Note that this class is deprecated. ```tsx import { NotFoundRoute, createRouter } from '@tanstack/react-router' import { Route as rootRoute } from './routes/__root' import { routeTree } from './routeTree.gen' const notFoundRoute = new NotFoundRoute({ getParentRoute: () => rootRoute, component: () => <div>Not found!!!</div>, }) const router = createRouter({ routeTree, notFoundRoute, }) // ... other code ``` -------------------------------- ### Install TanStack Router package Source: https://tanstack.com/router/latest/docs/quick-start.md Add the required router package to your existing project dependencies. ```bash @tanstack/react-router ``` ```bash @tanstack/solid-router ``` -------------------------------- ### Server Middleware with Input/Output Rewrites Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md URL rewrites are applied on both client and server. This example shows server middleware configuration for input and output rewrites, using `deLocalizeUrl` and `localizeUrl`. ```tsx // router.tsx export const router = createRouter({ routeTree, rewrite: { input: ({ url }) => deLocalizeUrl(url), output: ({ url }) => localizeUrl(url), }, }) ``` -------------------------------- ### Single-Page Applications - React Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md Example of rendering `<HeadContent />` in a React single-page application. ```APIDOC ## Single-Page Applications - React ### Description Example of rendering `<HeadContent />` in a React single-page application. Ensure the `<title>` tag is removed from `index.html` if present. ### Method N/A (Component Integration) ### Endpoint N/A (Component Integration) ### Request Example ```tsx import { HeadContent } from '@tanstack/react-router' const rootRoute = createRootRoute({ component: () => ( <> <HeadContent /> <Outlet /> </> ), }) ``` ### Response N/A (Component Integration) ``` -------------------------------- ### Directory Structure for Pathless Route Groups Source: https://tanstack.com/router/latest/docs/routing/routing-concepts.md This example shows a typical file structure using pathless route group directories. The `(app)` and `(auth)` directories are purely for organization and do not influence routing. ```directory routes/ ├── index.tsx ├── (app)/ │ ├── dashboard.tsx │ ├── settings.tsx │ ├── users.tsx ├── (auth)/ │ ├── login.tsx │ ├── register.tsx ``` -------------------------------- ### Defining a Route with the Route Class Source: https://tanstack.com/router/latest/docs/api/router/RouteClass.md This example demonstrates how to instantiate a new Route using the Route class constructor. It includes defining the parent route, path, a loader function, and a React component that consumes the loader data. ```tsx import { Route } from '@tanstack/react-router' import { rootRoute } from './__root' const indexRoute = new Route({ getParentRoute: () => rootRoute, path: '/', loader: () => { return 'Hello World' }, component: IndexComponent, }) function IndexComponent() { const data = indexRoute.useLoaderData() return <div>{data}</div> } ``` -------------------------------- ### Define a pseudo route tree Source: https://tanstack.com/router/latest/docs/routing/route-matching.md An example of an unsorted route tree structure. ```text Root - blog - $postId - / - new - / - * - about - about/us ``` -------------------------------- ### Install TanStack Router Dependencies Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-location.md Install the necessary TanStack Router packages using npm. This replaces React Location dependencies. ```sh npm install @tanstack/react-router @tanstack/router-devtools ``` ```sh npm uninstall @tanstack/react-location @tanstack/react-location-devtools ``` -------------------------------- ### Navigate with Path Params (Object Style) Source: https://tanstack.com/router/latest/docs/guide/path-params.md Provides an example of navigating to a route with path parameters using an object literal for the `params` prop in the `Link` component. ```tsx function Component() { return ( <Link to="/blog/$postId" params={{ postId: '123' }}> Post 123 </Link> ) } ``` -------------------------------- ### Example Nested Route Structure Source: https://tanstack.com/router/latest/docs/routing/route-trees.md Illustrates a hierarchical route structure for a blog section, showing how nested URLs map to nested components. ```tsx ├── blog │ ├── posts │ │ ├── $postId ``` -------------------------------- ### Setup TanStack Router with SSR Query Integration (React) Source: https://tanstack.com/router/latest/docs/integrations/query.md Configure your router with a new QueryClient and set up the SSR query integration. Ensure a fresh QueryClient is created per request in SSR environments. The integration can optionally wrap your router with QueryClientProvider. ```tsx import { QueryClient } from '@tanstack/react-query' import { createRouter } from '@tanstack/react-router' import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query' import { routeTree } from './routeTree.gen' export function getRouter() { const queryClient = new QueryClient() const router = createRouter({ routeTree, // optionally expose the QueryClient via router context context: { queryClient }, scrollRestoration: true, defaultPreload: 'intent', }) setupRouterSsrQueryIntegration({ router, queryClient, // optional: // handleRedirects: true, // wrapQueryClient: true, }) return router } ``` -------------------------------- ### Implementing a Root Route with Outlet Source: https://tanstack.com/router/latest/docs/guide/outlets.md This example demonstrates how to define a root route component that includes a static header and an Outlet component where nested child routes will be injected. It shows the implementation for both React and Solid frameworks. ```tsx import { createRootRoute, Outlet } from '@tanstack/react-router' export const Route = createRootRoute({ component: RootComponent, }) function RootComponent() { return ( <div> <h1>My App</h1> <Outlet /> </div> ) } ``` ```tsx import { createRootRoute, Outlet } from '@tanstack/solid-router' export const Route = createRootRoute({ component: RootComponent, }) function RootComponent() { return ( <div> <h1>My App</h1> <Outlet /> </div> ) } ``` -------------------------------- ### Get Type-Safe Route Hooks with getRouteApi (TypeScript/React) Source: https://tanstack.com/router/latest/docs/api/router/getRouteApiFunction.md Demonstrates how to use the getRouteApi function to obtain a RouteApi instance. This instance provides type-safe access to hooks like useLoaderData, pre-bound to a specific route ID ('/posts' in this example). This simplifies data fetching and manipulation within components tied to that route. ```tsx import { getRouteApi } from '@tanstack/react-router' const routeApi = getRouteApi('/posts') export function PostsPage() { const posts = routeApi.useLoaderData() // ... } ``` -------------------------------- ### Install TanStack Router ESLint Plugin Source: https://tanstack.com/router/latest/docs/eslint/eslint-plugin-router.md Install the TanStack Router ESLint plugin as a development dependency. This plugin helps enforce best practices and prevent common mistakes when using TanStack Router. ```bash npm install -D @tanstack/eslint-plugin-router yarn add -D @tanstack/eslint-plugin-router pnpm add -D @tanstack/eslint-plugin-router ``` -------------------------------- ### Subscribing to Router Events Source: https://tanstack.com/router/latest/docs/api/router/RouterEventsType.md An example demonstrating how to subscribe to router events, specifically the 'onResolved' event, and access its payload. ```APIDOC ## Example ```typescript import { createRouter } from '@tanstack/react-router' import { routeTree } from './routeTree.gen' const router = createRouter({ routeTree }) const unsub = router.subscribe('onResolved', (evt) => { // ... }) ``` ``` -------------------------------- ### Solid Authentication using Context and Hooks Source: https://tanstack.com/router/latest/docs/guide/authenticated-routes.md This example demonstrates how to integrate authentication state managed by Solid context and hooks into TanStack Router. It involves defining a router context, passing the authentication state down via the RouterProvider, and using it to protect routes. ```tsx import { createRootRouteWithContext, Outlet } from '@tanstack/solid-router'; interface MyRouterContext { auth: AuthState } export const Route = createRootRouteWithContext<MyRouterContext>()({ component: () => <Outlet />, }); ``` ```tsx import { createRouter } from '@tanstack/solid-router'; import { routeTree } from './routeTree.gen'; export const router = createRouter({ routeTree, context: { auth: undefined!, }, }); ``` ```tsx import { RouterProvider } from '@tanstack/solid-router'; import { AuthProvider, useAuth } from './auth'; import { router } from './router'; function InnerApp() { const auth = useAuth(); return <RouterProvider router={router} context={{ auth }} />; } function App() { return ( <AuthProvider> <InnerApp /> </AuthProvider> ); } ``` -------------------------------- ### useBlocker with Custom UI and Resolver Source: https://tanstack.com/router/latest/docs/api/router/useBlockerHook.md This example shows how to use the useBlocker hook with 'withResolver: true' to enable custom UI feedback. When navigation is blocked, it displays a confirmation message and provides 'proceed' and 'reset' buttons for user interaction. ```tsx import { useBlocker } from '@tanstack/react-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = useState(false) const { proceed, reset, status, next } = useBlocker({ shouldBlockFn: () => formIsDirty, withResolver: true, }) // ... return ( <> {/* ... */} {status === 'blocked' && ( <div> <p>You are navigating to {next.pathname}</p> <p>Are you sure you want to leave?</p> <button onClick={proceed}>Yes</button> <button onClick={reset}>No</button> </div> )} </> ) } ``` -------------------------------- ### TanStack Start Server Middleware for i18n Source: https://tanstack.com/router/latest/docs/guide/internationalization-i18n.md Implements server-side internationalization using Paraglide's middleware in a TanStack Start application. This ensures locale is handled correctly during server requests. ```ts import { paraglideMiddleware } from './paraglide/server' export default { fetch(req: Request) { return paraglideMiddleware(req, () => handler.fetch(req)) }, } ``` -------------------------------- ### composeRewrites Function Example Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Demonstrates how to use the `composeRewrites` function to combine multiple rewrite configurations into a single one. Input rewrites execute sequentially, while output rewrites execute in reverse order. ```typescript import { composeRewrites } from '@tanstack/react-router' function composeRewrites(rewrites: Array<LocationRewrite>): LocationRewrite const composedRewrite = composeRewrites([ { input: rewrite1Input, output: rewrite1Output }, { input: rewrite2Input, output: rewrite2Output }, ]) // Input execution order: rewrite1Input → rewrite2Input // Output execution order: rewrite2Output → rewrite1Output ``` -------------------------------- ### createLink with MUI (Material-UI) Source: https://tanstack.com/router/latest/docs/guide/custom-link.md References an example demonstrating the integration of `createLink` with Material-UI (MUI) components for creating custom, type-safe links within a TanStack Router application. ```APIDOC ## createLink with MUI (Material-UI) ### Description This section points to an external example showcasing how to use `createLink` with Material-UI (MUI) components. This integration allows for creating custom links that benefit from MUI's styling and component system while maintaining TanStack Router's type safety. ### Method N/A (This is a component creation example) ### Endpoint N/A ### Parameters N/A ### Request Example Refer to the [example](https://github.com/TanStack/router/tree/main/examples/react/start-material-ui) for detailed implementation. ### Response N/A (This is a component creation example) ``` -------------------------------- ### Manual Mutation Reset with router.subscribe Source: https://tanstack.com/router/latest/docs/guide/data-mutations.md This example shows how to manually reset mutation states using the `router.subscribe` method and the `onResolved` event, useful for libraries without built-in keying. ```APIDOC ## Using the `router.subscribe` method ### Description For mutation libraries that do not support a keying mechanism, this approach demonstrates how to manually reset mutation states. It utilizes TanStack Router's `subscribe` method to listen for route changes and clear mutation states when they are no longer needed. ### Method Not applicable (Client-side logic) ### Endpoint Not applicable (Client-side logic) ### Parameters Not applicable ### Request Example ```tsx const router = createRouter() const coolMutationCache = createCoolMutationCache() const unsubscribeFn = router.subscribe('onResolved', () => { // Reset mutation states when the route changes coolMutationCache.clear() }) // To unsubscribe later: unsubscribeFn() ``` ### Response Not applicable (Client-side logic) ``` -------------------------------- ### Initialize TanStack Router in Solid Source: https://tanstack.com/router/latest/docs/installation/manual.md Sets up the root route, child routes, and router instance, then renders the application to the DOM. ```tsx /* @refresh reload */ import { render } from 'solid-js/web' import { Outlet, RouterProvider, Link, createRouter, createRoute, createRootRoute, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' const rootRoute = createRootRoute({ component: () => ( <> <div class="p-2 flex gap-2"> <Link to="/" class="[&.active]:font-bold"> Home </Link>{' '} <Link to="/about" class="[&.active]:font-bold"> About </Link> </div> <hr /> <Outlet /> <TanStackRouterDevtools /> </> ), }) const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', component: function Index() { return ( <div class="p-2"> <h3>Welcome Home!</h3> </div> ) }, }) const aboutRoute = createRoute({ getParentRoute: () => rootRoute, path: '/about', component: function About() { return <div class="p-2">Hello from About!</div> }, }) const routeTree = rootRoute.addChildren([indexRoute, aboutRoute]) const router = createRouter({ routeTree }) declare module '@tanstack/solid-router' { interface Register { router: typeof router } } const rootElement = document.getElementById('app')! render(() => <RouterProvider router={router} />, rootElement) ``` -------------------------------- ### Paraglide JS Vite Plugin Setup Source: https://tanstack.com/router/latest/docs/guide/internationalization-i18n.md Shows how to integrate the Paraglide JS Vite plugin into your project for type-safe translations. This involves importing the plugin and configuring the project and output directory. ```bash npx @inlang/paraglide-js@latest init ``` ```ts import { paraglideVitePlugin } from '@inlang/paraglide-js' paraglideVitePlugin({ project: './project.inlang', outdir: './app/paraglide', }) ``` -------------------------------- ### Creating a Root Route Instance with TanStack Router Source: https://tanstack.com/router/latest/docs/api/router/RootRouteClass.md This example demonstrates how to instantiate the deprecated RootRoute class to create the root of a route tree. It imports necessary components from '@tanstack/react-router', defines the root route with a basic component, and then adds child routes to form the complete route tree, which is finally used to initialize the router. ```tsx import { RootRoute, createRouter, Outlet } from '@tanstack/react-router' const rootRoute = new RootRoute({ component: () => <Outlet />, // ... root route options }) const routeTree = rootRoute.addChildren([ // ... other routes ]) const router = createRouter({ routeTree, }) ``` -------------------------------- ### Recommended Legacy Config Setup for ESLint Source: https://tanstack.com/router/latest/docs/eslint/eslint-plugin-router.md Configure ESLint using the legacy .eslintrc format to enable all recommended rules from the TanStack Router ESLint plugin. This is suitable for projects not yet migrated to flat config. ```json { "extends": ["plugin:@tanstack/eslint-plugin-router/recommended"] } ``` -------------------------------- ### Custom Flat Config Setup for ESLint Source: https://tanstack.com/router/latest/docs/eslint/eslint-plugin-router.md Manually configure ESLint with the TanStack Router plugin and specify individual rules. This allows for fine-grained control over which rules are enabled. ```javascript import pluginRouter from '@tanstack/eslint-plugin-router' export default [ { plugins: { '@tanstack/router': pluginRouter, }, rules: { '@tanstack/router/create-route-property-order': 'error', }, }, // Any other config... ] ``` -------------------------------- ### Using the Await component with deferred data Source: https://tanstack.com/router/latest/docs/api/router/awaitComponent.md This example demonstrates how to use the Await component to handle a deferred promise from a loader. It takes a promise prop and a render function that receives the resolved data. ```tsx import { Await } from '@tanstack/react-router' function Component() { const { deferredPromise } = route.useLoaderData() return ( <Await promise={deferredPromise}> {(data) => <div>{JSON.stringify(data)}</div>} </Await> ) } ``` -------------------------------- ### Define Route Prefixes Source: https://tanstack.com/router/latest/docs/guide/path-params.md Matches URL segments starting with a static prefix followed by a dynamic parameter. ```tsx export const Route = createFileRoute('/posts/post-{$postId}')({ component: PostComponent, }) function PostComponent() { const { postId } = Route.useParams() // postId will be the value after 'post-' return <div>Post ID: {postId}</div> } ``` ```tsx export const Route = createFileRoute('/posts/post-{$postId}')({ component: PostComponent, }) function PostComponent() { const params = Route.useParams() // postId will be the value after 'post-' return <div>Post ID: {params().postId}</div> } ``` -------------------------------- ### Custom Legacy Config Setup for ESLint Source: https://tanstack.com/router/latest/docs/eslint/eslint-plugin-router.md Manually configure ESLint with the TanStack Router plugin in the legacy .eslintrc format, specifying individual rules. This provides flexibility in rule selection. ```json { "plugins": ["@tanstack/eslint-plugin-router"], "rules": { "@tanstack/router/create-route-property-order": "error" } } ``` -------------------------------- ### Scaffold a new project with CLI Source: https://tanstack.com/router/latest/docs/quick-start.md Use the TanStack CLI to initialize a new router-only project for React or Solid. ```bash @tanstack/cli create --router-only ``` ```bash @tanstack/cli create --router-only --framework solid ``` -------------------------------- ### Define Route with Type-Safe Redirect (TypeScript) Source: https://tanstack.com/router/latest/docs/api/router/RouteType.md This example demonstrates how to define a route using `createFileRoute` and implement a type-safe redirect using `Route.redirect`. It shows how to conditionally redirect users based on context, ensuring type safety for relative paths. ```typescript import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/dashboard/settings')({ beforeLoad: ({ context }) => { if (!context.user) { // Type-safe redirect - 'from' is automatically '/dashboard/settings' throw Route.redirect({ to: '../login', // Relative path to sibling route }) } }, }) ``` -------------------------------- ### Basic useBlocker Hook Usage Source: https://tanstack.com/router/latest/docs/api/router/useBlockerHook.md This example demonstrates the basic usage of the useBlocker hook. It blocks navigation when the 'formIsDirty' state is true. No custom UI or resolver is used, relying on the default behavior. ```tsx import { useBlocker } from '@tanstack/react-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = useState(false) useBlocker({ shouldBlockFn: () => formIsDirty, }) // ... } ``` -------------------------------- ### Declarative Route Masking with routeMasks Source: https://tanstack.com/router/latest/docs/guide/route-masking.md Example of configuring route masks declaratively using the `routeMasks` option in the `createRouter` function. ```APIDOC ## PUT /api/users/{userId} ### Description Updates an existing user's information. ### Method PUT ### Endpoint /api/users/{userId} ### Parameters #### Path Parameters - **userId** (string) - Required - The unique identifier of the user to update. #### Request Body - **username** (string) - Optional - The updated username. - **email** (string) - Optional - The updated email address. ### Request Example ```json { "email": "john.doe.updated@example.com" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the user. - **username** (string) - The updated username. - **email** (string) - The updated email address. - **updatedAt** (string) - The timestamp when the user was last updated. #### Response Example ```json { "id": "user-12345", "username": "johndoe", "email": "john.doe.updated@example.com", "updatedAt": "2023-10-27T11:30:00Z" } ``` ``` -------------------------------- ### Integrate Chakra UI Link with createLink Source: https://tanstack.com/router/latest/docs/guide/custom-link.md Example of wrapping a Chakra UI Link component to apply custom styles and default preloading behavior. ```tsx import * as React from 'react' import { createLink, LinkComponent } from '@tanstack/react-router' import { Link } from '@chakra-ui/react' interface ChakraLinkProps extends Omit<React.ComponentPropsWithoutRef<typeof Link>, 'href'> {} const ChakraLinkComponent = React.forwardRef<HTMLAnchorElement, ChakraLinkProps>((props, ref) => { return <Link ref={ref} {...props} /> }) const CreatedLinkComponent = createLink(ChakraLinkComponent) export const CustomLink: LinkComponent<typeof ChakraLinkComponent> = (props) => { return ( <CreatedLinkComponent textDecoration={'underline'} _hover={{ textDecoration: 'none' }} _focus={{ textDecoration: 'none' }} preload={'intent'} {...props} /> ) } ``` -------------------------------- ### createLink with Chakra UI Source: https://tanstack.com/router/latest/docs/guide/custom-link.md Provides an example of creating a custom Link component using `createLink` that integrates with Chakra UI components, allowing for Chakra's styling props and theming. ```APIDOC ## createLink with Chakra UI ### Description This example demonstrates how to create a custom `Link` component that integrates with Chakra UI. By using `createLink`, you can apply Chakra UI's styling props and theme customizations to your router links while maintaining type safety. ### Method N/A (This is a component creation example) ### Endpoint N/A ### Parameters N/A ### Request Example ```tsx import * as React from 'react'; import { createLink, LinkComponent } from '@tanstack/react-router'; import { Link } from '@chakra-ui/react'; interface ChakraLinkProps extends Omit< React.ComponentPropsWithoutRef<typeof Link>, 'href' > { // Add any additional props you want to pass to the link } const ChakraLinkComponent = React.forwardRef< HTMLAnchorElement, ChakraLinkProps >((props, ref) => { return <Link ref={ref} {...props} />; }); const CreatedLinkComponent = createLink(ChakraLinkComponent); export const CustomLink: LinkComponent<typeof ChakraLinkComponent> = ( props, ) => { return ( <CreatedLinkComponent textDecoration={'underline'} _hover={{ textDecoration: 'none' }} _focus={{ textDecoration: 'none' }} preload={'intent'} {...props} /> ); } ``` ### Response N/A (This is a component creation example) ``` -------------------------------- ### Accessing a Route Match Source: https://tanstack.com/router/latest/docs/api/router/useMatchHook.md Example of how to use the `useMatch` hook to access a specific route match based on its ID. ```APIDOC ## Example: Accessing a route match ### Description This example demonstrates how to use the `useMatch` hook to get the `RouteMatch` object for a specific route, like `/posts/$postId`. ### Code ```tsx import { useMatch } from '@tanstack/react-router' function Component() { const match = useMatch({ from: '/posts/$postId' }) // match is a strict RouteMatch object // ... } ``` ``` -------------------------------- ### Retain All Search Params Example Source: https://tanstack.com/router/latest/docs/api/router/retainSearchParamsFunction.md Illustrates using retainSearchParams with `true` to retain all search parameters in a file route. ```APIDOC ## retainSearchParams Middleware (Retain All) ### Description This example shows how to use `retainSearchParams(true)` to ensure all existing search parameters are carried over during navigation within a file route. ### Method Configuration within `createFileRoute`'s `search.middlewares` property. ### Endpoint N/A (Middleware configuration) ### Parameters - **retainSearchParams** (`true`) - Required - When set to `true`, all search parameters will be retained. ### Request Example ```tsx import { z } from 'zod' import { createFileRoute, retainSearchParams } from '@tanstack/react-router' const searchSchema = z.object({ one: z.string().optional(), two: z.string().optional(), }) export const Route = createFileRoute('/')({ validateSearch: searchSchema, search: { middlewares: [ retainSearchParams(true) // Retains all search params ], }, }) ``` ### Response N/A (Middleware configuration) #### Response Example N/A ``` -------------------------------- ### Realistic Data Loading with TanStack Query (React) Source: https://tanstack.com/router/latest/docs/guide/external-data-loading.md A more practical example demonstrating data loading using TanStack Query with TanStack Router. It utilizes `queryClient.ensureQueryData` in the loader to prefetch data and `useSuspenseQuery` in the component to consume it, ensuring data is available upon render. ```tsx const postsQueryOptions = queryOptions({ queryKey: ['posts'], queryFn: () => fetchPosts(), }) export const Route = createFileRoute('/posts')({ // Use the `loader` option to ensure that the data is loaded loader: () => queryClient.ensureQueryData(postsQueryOptions), component: () => { // Read the data from the cache and subscribe to updates const { data: { posts }, } = useSuspenseQuery(postsQueryOptions) return ( <div> {posts.map((post) => ( <Post key={post.id} post={post} /> ))} </div> ) }, }) ``` -------------------------------- ### Imperative Route Masking with Link Source: https://tanstack.com/router/latest/docs/guide/route-masking.md Example of using the `mask` option with the `<Link>` component to mask a route. ```APIDOC ## POST /api/users ### Description Creates a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The username for the new user. - **email** (string) - Required - The email address for the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "user-12345", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Imperative Route Masking with navigate() Source: https://tanstack.com/router/latest/docs/guide/route-masking.md Example of using the `mask` option with the `navigate()` API function to mask a route. ```APIDOC ## GET /api/users/{userId} ### Description Retrieves details for a specific user. ### Method GET ### Endpoint /api/users/{userId} ### Parameters #### Path Parameters - **userId** (string) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the user. - **username** (string) - The username of the user. - **email** (string) - The email address of the user. - **createdAt** (string) - The timestamp when the user was created. #### Response Example ```json { "id": "user-12345", "username": "johndoe", "email": "john.doe@example.com", "createdAt": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Creating a Root Route with Context - TypeScript/React Source: https://tanstack.com/router/latest/docs/api/router/createRootRouteWithContextFunction.md This example demonstrates how to use createRootRouteWithContext to define a root route that requires a specific context type (MyRouterContext). It shows the import statements, context interface definition, route creation, and router instantiation with the provided context. ```tsx import { createRootRouteWithContext, createRouter, } from '@tanstack/react-router' import { QueryClient } from '@tanstack/react-query' interface MyRouterContext { queryClient: QueryClient } const rootRoute = createRootRouteWithContext<MyRouterContext>()({ component: () => <Outlet />, // ... root route options }) const routeTree = rootRoute.addChildren([ // ... other routes ]) const queryClient = new QueryClient() const router = createRouter({ routeTree, context: { queryClient, }, }) ``` -------------------------------- ### Render Client-Only Components with TanStack Router Source: https://tanstack.com/router/latest/docs/api/router/clientOnlyComponent.md This example demonstrates how to use the ClientOnly component to wrap a component that would otherwise cause hydration errors. It utilizes the fallback prop to provide a placeholder while the main component loads. ```tsx import { ClientOnly, createFileRoute } from '@tanstack/react-router' import { Charts, FallbackCharts } from './charts-that-break-server-side-rendering' export const Route = createFileRoute('/dashboard')({ component: Dashboard, }) function Dashboard() { return ( <div> <p>Dashboard</p> <ClientOnly fallback={<FallbackCharts />}> <Charts /> </ClientOnly> </div> ) } ``` -------------------------------- ### useBlocker with Conditional Path Blocking Source: https://tanstack.com/router/latest/docs/api/router/useBlockerHook.md This example demonstrates conditional blocking using the 'shouldBlockFn'. Navigation is blocked unless the next path includes '/step/'. It also utilizes 'withResolver: true' for custom UI confirmation. ```tsx import { useBlocker } from '@tanstack/react-router' function MyComponent() { const { proceed, reset, status } = useBlocker({ shouldBlockFn: ({ next }) => { return !next.pathname.includes('step/') }, withResolver: true, }) // ... return ( <> {/* ... */} {status === 'blocked' && ( <div> <p>Are you sure you want to leave?</p> <button onClick={proceed}>Yes</button> <button onClick={reset}>No</button> </div> )} </> ) } ``` -------------------------------- ### Define and Implement a Lazy Route Source: https://tanstack.com/router/latest/docs/api/router/createLazyRouteFunction.md This example demonstrates how to define a lazy route in a separate file using createLazyRoute and then integrate it into the main route tree using the lazy method. ```tsx // src/route-pages/index.tsx import { createLazyRoute } from '@tanstack/react-router' export const Route = createLazyRoute('/')({ component: IndexComponent, }) function IndexComponent() { const data = Route.useLoaderData() return <div>{data}</div> } // src/routeTree.tsx import { createRootRouteWithContext, createRoute, Outlet, } from '@tanstack/react-router' interface MyRouterContext { foo: string } const rootRoute = createRootRouteWithContext<MyRouterContext>()({ component: () => <Outlet />, }) const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', }).lazy(() => import('./route-pages/index').then((d) => d.Route)) export const routeTree = rootRoute.addChildren([indexRoute]) ``` -------------------------------- ### Implement HeadContent in Full-Stack Applications Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md Render the HeadContent component within the head tag of your root layout for full-stack applications using TanStack Start. ```tsx import { HeadContent } from '@tanstack/react-router' export const Route = createRootRoute({ component: () => ( <html> <head> <HeadContent /> </head> <body> <Outlet /> </body> </html> ), }) ``` ```tsx import { HeadContent } from '@tanstack/solid-router' export const Route = createRootRoute({ component: () => ( <html> <head> <HeadContent /> </head> <body> <Outlet /> </body> </html> ), }) ``` -------------------------------- ### Create a file-based route using FileRoute Source: https://tanstack.com/router/latest/docs/api/router/FileRouteClass.md Demonstrates how to instantiate a FileRoute and configure it with a loader and a component. The instance must be exported as 'Route' for the TanStack Router CLI tools to generate the route tree correctly. ```tsx import { FileRoute } from '@tanstack/react-router' export const Route = new FileRoute('/').createRoute({ loader: () => { return 'Hello World' }, component: IndexComponent, }) function IndexComponent() { const data = Route.useLoaderData() return <div>{data}</div> } ``` -------------------------------- ### Register Router Instance with TanStack Router Source: https://tanstack.com/router/latest/docs/api/router/RegisterType.md This example shows how to register a router instance with TanStack Router using declaration merging. It adds the type of a created router to the `Register` interface, enabling enhanced type safety. ```typescript const router = createRouter({ // ... }) declare module '@tanstack/react-router' { interface Register { router: typeof router } } ``` -------------------------------- ### Initialize TanStack Router in React Source: https://tanstack.com/router/latest/docs/api/router/createRouterFunction.md Demonstrates how to instantiate a router using createRouter with a route tree and default configuration, then providing it to the application via RouterProvider. ```tsx import { createRouter, RouterProvider } from '@tanstack/react-router'; import { routeTree } from './routeTree.gen'; const router = createRouter({ routeTree, defaultPreload: 'intent', }); export default function App() { return <RouterProvider router={router} />; } ``` -------------------------------- ### Configure Route Masking with createRouteMask Source: https://tanstack.com/router/latest/docs/api/router/createRouteMaskFunction.md This example demonstrates how to define a route mask that maps a modal route to a standard photo URL. The resulting mask is then integrated into the router instance via the routeMasks option. ```tsx import { createRouteMask, createRouter } from '@tanstack/react-router'; const photoModalToPhotoMask = createRouteMask({ routeTree, from: '/photos/$photoId/modal', to: '/photos/$photoId', params: true, }); // Set up a Router instance const router = createRouter({ routeTree, routeMasks: [photoModalToPhotoMask], }); ``` -------------------------------- ### Create a Standard Root Route (Solid) Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md Initialize the root route for a Solid application using `createRootRoute` from `@tanstack/solid-router`. ```tsx // Standard root route import { createRootRoute } from '@tanstack/solid-router' const rootRoute = createRootRoute() ``` -------------------------------- ### Configure Vite Plugin for TanStack Router Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-location.md Install the TanStack Router Vite plugin and add it to your vite.config.js file to enable automatic route watching and updates. ```sh npm install -D @tanstack/router-plugin ``` ```javascript import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' export default defineConfig({ // ... plugins: [tanstackRouter(), react()], }) ``` -------------------------------- ### Retaining all search parameters with retainSearchParams Source: https://tanstack.com/router/latest/docs/api/router/retainSearchParamsFunction.md This example shows how to configure retainSearchParams to persist all search parameters by passing the boolean value true within a file route. ```tsx import { z } from 'zod' import { createFileRoute, retainSearchParams } from '@tanstack/react-router' const searchSchema = z.object({ one: z.string().optional(), two: z.string().optional(), }) export const Route = createFileRoute('/')({ validateSearch: searchSchema, search: { middlewares: [retainSearchParams(true)], }, }) ``` -------------------------------- ### Implement basic navigation blocking with useBlocker Source: https://tanstack.com/router/latest/docs/guide/navigation-blocking.md Use the useBlocker hook to conditionally prevent navigation when a form is in a dirty state. This example shows how to trigger a confirmation dialog before allowing the user to leave. ```tsx import { useBlocker } from '@tanstack/react-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = useState(false) useBlocker({ shouldBlockFn: () => { if (!formIsDirty) return false const shouldLeave = confirm('Are you sure you want to leave?') return !shouldLeave }, }) } ``` ```tsx import { useBlocker } from '@tanstack/solid-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = createSignal(false) useBlocker({ shouldBlockFn: () => { if (!formIsDirty()) return false const shouldLeave = confirm('Are you sure you want to leave?') return !shouldLeave }, }) } ``` -------------------------------- ### React Authentication using Context and Hooks Source: https://tanstack.com/router/latest/docs/guide/authenticated-routes.md This example demonstrates how to integrate authentication state managed by React context and hooks into TanStack Router. It involves defining a router context, passing the authentication state down via the RouterProvider, and using it to protect routes. ```tsx import { createRootRouteWithContext, Outlet } from '@tanstack/react-router'; interface MyRouterContext { auth: AuthState } export const Route = createRootRouteWithContext<MyRouterContext>()({ component: () => <Outlet />, }); ``` ```tsx import { createRouter } from '@tanstack/react-router'; import { routeTree } from './routeTree.gen'; export const router = createRouter({ routeTree, context: { auth: undefined!, }, }); ``` ```tsx import { RouterProvider } from '@tanstack/react-router'; import { AuthProvider, useAuth } from './auth'; import { router } from './router'; function InnerApp() { const auth = useAuth(); return <RouterProvider router={router} context={{ auth }} />; } function App() { return ( <AuthProvider> <InnerApp /> </AuthProvider> ); } ``` -------------------------------- ### Pass Initial Router Context (Solid) Source: https://tanstack.com/router/latest/docs/guide/router-context.md Initialize the router with a context object. This context is accessible by all routes and serves for dependency injection. ```tsx import { createRouter } from '@tanstack/solid-router' // Use the routerContext you created to create your router const router = createRouter({ routeTree, context: { user: { id: '123', name: 'John Doe', }, }, }) ``` -------------------------------- ### Link Component with Locale Rewrite Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md The Link component automatically applies output rewrites. This example shows how a configured locale rewrite adds a prefix to the href. ```tsx // With locale rewrite configured (adds /en prefix) <Link to="/about">About</Link> // Renders: <a href="/en/about">About</a> ``` -------------------------------- ### Configure Esbuild for Solid with TanStack Router Source: https://tanstack.com/router/latest/docs/installation/with-esbuild.md Integrate the tanstackRouter plugin into your Esbuild build process for Solid applications. This setup includes the solidPlugin and enables auto code splitting. ```javascript import * as esbuild from 'esbuild' import { solidPlugin } from 'esbuild-plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/esbuild' const isDev = process.argv.includes('--dev') const ctx = await esbuild.context({ entryPoints: ['src/main.tsx'], outfile: 'dist/main.js', minify: !isDev, bundle: true, format: 'esm', target: ['esnext'], sourcemap: true, plugins: [ solidPlugin(), tanstackRouter({ target: 'solid', autoCodeSplitting: true }), ], }) if (isDev) { await ctx.watch() const { host, port } = await ctx.serve({ servedir: '.', port: 3005 }) console.log(`Server running at http://${host || 'localhost'}:${port}`) } else { await ctx.rebuild() await ctx.dispose() } ``` -------------------------------- ### Create Route Instance with Options - React (TypeScript) Source: https://tanstack.com/router/latest/docs/api/router/createRouteFunction.md This example demonstrates how to use the createRoute function to create a root route instance in a React application using TypeScript. It configures the parent route, path, loader, and component for the index route. ```tsx import { createRoute } from '@tanstack/react-router' import { rootRoute } from './__root' const Route = createRoute({ getParentRoute: () => rootRoute, path: '/', loader: () => { return 'Hello World' }, component: IndexComponent, }) function IndexComponent() { const data = Route.useLoaderData() return <div>{data}</div> } ``` -------------------------------- ### Basic Link Navigation with Parameters Source: https://tanstack.com/router/latest/docs/api/router/linkComponent.md Demonstrates how to use the Link component to navigate to a route with dynamic path parameters and updated search parameters. It shows the integration within a React component. ```tsx import { Link } from '@tanstack/react-router' function Component() { return ( <Link to="/somewhere/$somewhereId" params={{ somewhereId: 'baz' }} search={(prev) => ({ ...prev, foo: 'bar' })} > Click me </Link> ) } ``` -------------------------------- ### Create Root Route with Context (React) Source: https://tanstack.com/router/latest/docs/api/router/rootRouteWithContextFunction.md Demonstrates how to use the deprecated `rootRouteWithContext` function to create a root route that requires a specific context type (e.g., QueryClient) when initializing the router. This setup is useful for providing shared resources to your application's routes. ```tsx import { rootRouteWithContext, createRouter } from '@tanstack/react-router' import { QueryClient } from '@tanstack/react-query' interface MyRouterContext { queryClient: QueryClient } const rootRoute = rootRouteWithContext<MyRouterContext>()({ component: () => <Outlet />, // ... root route options }) const routeTree = rootRoute.addChildren([ // ... other routes ]) const queryClient = new QueryClient() const router = createRouter({ routeTree, context: { queryClient, }, }) ``` -------------------------------- ### CatchNotFound Component Usage Example Source: https://tanstack.com/router/latest/docs/api/router/catchNotFoundComponent.md Demonstrates how to use the CatchNotFound component to wrap a component that might throw a not-found error. It shows how to provide a fallback component and an optional error handling callback. ```tsx import { CatchNotFound } from '@tanstack/react-router' function Component() { return ( <CatchNotFound fallback={(error) => <p>Not found error! {JSON.stringify(error)}</p>} > <ComponentThatMightThrowANotFoundError /> </CatchNotFound> ) } ``` -------------------------------- ### Retrieve child matches with useChildMatches Source: https://tanstack.com/router/latest/docs/api/router/useChildMatchesHook.md This example demonstrates the basic usage of the useChildMatches hook to access an array of child route matches within a React component. ```tsx import { useChildMatches } from '@tanstack/react-router'; function Component() { const childMatches = useChildMatches(); // Access child route matches here } ``` -------------------------------- ### Accessing Search Parameters with useSearch Source: https://tanstack.com/router/latest/docs/api/router/useSearchHook.md Demonstrates how to retrieve search parameters using the useSearch hook. It includes examples for specific route targeting, using the select option for data transformation, and enabling loose typing. ```tsx import { useSearch } from '@tanstack/react-router' function Component() { const search = useSearch({ from: '/posts/$postId' }) const selected = useSearch({ from: '/posts/$postId', select: (search) => search.postView, }) const looseSearch = useSearch({ strict: false }) } ``` -------------------------------- ### Create Router with Context in Solid Source: https://tanstack.com/router/latest/docs/guide/data-loading.md Instantiate the router using `createRouter`, providing the `routeTree` and fulfilling the type requirements of the `routerContext` by supplying necessary functions like `fetchPosts`. ```tsx import { routeTree } from './routeTree.gen' // Use your routerContext to create a new router // This will require that you fullfil the type requirements of the routerContext const router = createRouter({ routeTree, context: { // Supply the fetchPosts function to the router context fetchPosts, }, }) ``` -------------------------------- ### Main Application Entry Point with TanStack Router Source: https://tanstack.com/router/latest/docs/installation/manual.md Sets up the main entry point for a React application using TanStack Router. It creates a router instance from the generated route tree and renders the application with the RouterProvider. ```typescript import { StrictMode } from 'react' import ReactDOM from 'react-dom/client' import { RouterProvider, createRouter } from '@tanstack/react-router' // Import the generated route tree import { routeTree } from './routeTree.gen' // Create a new router instance const router = createRouter({ routeTree }) // Register the router instance for type safety declare module '@tanstack/react-router' { interface Register { router: typeof router } } // Render the app const rootElement = document.getElementById('root')! if (!rootElement.innerHTML) { const root = ReactDOM.createRoot(rootElement) root.render( <StrictMode> <RouterProvider router={router} /> </StrictMode>, ) } ``` -------------------------------- ### Conditionally render a back button using useCanGoBack Source: https://tanstack.com/router/latest/docs/api/router/useCanGoBack.md This example demonstrates how to use the useCanGoBack hook to check if navigation history exists and conditionally render a button that triggers the router's history.back() method. ```tsx import { useRouter, useCanGoBack } from '@tanstack/react-router' function Component() { const router = useRouter() const canGoBack = useCanGoBack() return ( <div> {canGoBack ? ( <button onClick={() => router.history.back()}>Go back</button> ) : null} </div> ) } ``` -------------------------------- ### useBlocker Without Resolver Source: https://tanstack.com/router/latest/docs/api/router/useBlockerHook.md This example shows the useBlocker hook without using the 'withResolver' option. The 'shouldBlockFn' directly uses the browser's 'confirm' dialog to ask the user if they want to leave. ```tsx import { useBlocker } from '@tanstack/react-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = useState(false) useBlocker({ shouldBlockFn: ({ next }) => { if (next.pathname.includes('step/')) { return false } const shouldLeave = confirm('Are you sure you want to leave?') return !shouldLeave }, }) // ... } ``` -------------------------------- ### Link Component with Hostname Rewrite Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md When an output rewrite changes the hostname, the Link component renders a standard anchor tag for hard navigation. This example shows a rewrite for '/admin' paths to 'admin.example.com'. ```tsx // Rewrite that changes hostname for /admin paths const router = createRouter({ routeTree, rewrite: { output: ({ url }) => { if (url.pathname.startsWith('/admin')) { url.hostname = 'admin.example.com' url.pathname = url.pathname.replace(/^\/admin/, '') || '/' } return url }, }, }) // This link will be a hard navigation (full page load) <Link to="/admin/dashboard">Admin Dashboard</Link> // Renders: <a href="https://admin.example.com/dashboard">Admin Dashboard</a> ``` -------------------------------- ### Naive Data Loading with Route Loader (React) Source: https://tanstack.com/router/latest/docs/guide/external-data-loading.md An illustrative example of using a route's `loader` option to seed a cache with data. This approach is flawed but demonstrates the concept of preloading data before the component renders. It directly manipulates a global cache variable. ```tsx let postsCache = [] export const Route = createFileRoute('/posts')({ loader: async () => { postsCache = await fetchPosts() }, component: () => { return ( <div> {postsCache.map((post) => ( <Post key={post.id} post={post} /> ))} </div> ) }, }) ``` -------------------------------- ### Imperative Navigation with useNavigate Source: https://tanstack.com/router/latest/docs/guide/navigation.md Use the `useNavigate` hook to get a `navigate` function for imperative navigation, typically from side effects after an async action. Specify the `from` route option to reduce potential errors. ```tsx function Component() { const navigate = useNavigate({ from: '/posts/$postId' }) const handleSubmit = async (e: FrameworkFormEvent) => { e.preventDefault() const response = await fetch('/posts', { method: 'POST', body: JSON.stringify({ title: 'My First Post' }), }) const { id: postId } = await response.json() if (response.ok) { navigate({ to: '/posts/$postId', params: { postId } }) } } } ``` -------------------------------- ### Initialize Router Instance Source: https://tanstack.com/router/latest/docs/guide/creating-a-router.md Creates a new Router instance using the framework-specific package. This instance manages the route tree and global router configuration. ```tsx import { createRouter } from '@tanstack/react-router' const router = createRouter({ // ... }) ``` ```tsx import { createRouter } from '@tanstack/solid-router' const router = createRouter({ // ... }) ``` -------------------------------- ### Accessing Route Loader Data with useLoaderData Source: https://tanstack.com/router/latest/docs/api/router/useLoaderDataHook.md This example demonstrates how to use the useLoaderData hook to retrieve data from a specific route match. By providing the 'from' option, the hook ensures type safety for the returned loader data. ```tsx import { useLoaderData } from '@tanstack/react-router' function Component() { const loaderData = useLoaderData({ from: '/posts/$postId' }) // loaderData is typed based on the route definition } ``` -------------------------------- ### Language Switching Link Component Source: https://tanstack.com/router/latest/docs/guide/internationalization-i18n.md Provides an example of a Link component that toggles the locale parameter between 'en' and 'fr'. This allows users to switch languages dynamically within the application. ```tsx <Link to="/{-$locale}/blog/{-$category}/$slug" params={(prev) => ({ ...prev, locale: prev.locale === 'en' ? undefined : 'fr', })}> Français </Link> ``` -------------------------------- ### React Code-Based Route Configuration Source: https://tanstack.com/router/latest/docs/installation/manual.md Configures routes using code for a React application, including a root layout, index, and about routes. This example uses code-based generation and requires a root element with id 'app'. ```tsx import { StrictMode } from 'react' import ReactDOM from 'react-dom/client' import { Outlet, RouterProvider, Link, createRouter, createRoute, createRootRoute, } from '@tanstack/react-router' import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' const rootRoute = createRootRoute({ component: () => ( <> <div className="p-2 flex gap-2"> <Link to="/" className="[&.active]:font-bold"> Home </Link>{' '} <Link to="/about" className="[&.active]:font-bold"> About </Link> </div> <hr /> <Outlet /> <TanStackRouterDevtools /> </> ), }) const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', component: function Index() { return ( <div className="p-2"> <h3>Welcome Home!</h3> </div> ) }, }) const aboutRoute = createRoute({ getParentRoute: () => rootRoute, path: '/about', component: function About() { return <div className="p-2">Hello from About!</div> }, }) const routeTree = rootRoute.addChildren([indexRoute, aboutRoute]) const router = createRouter({ routeTree }) declare module '@tanstack/react-router' { interface Register { router: typeof router } } const rootElement = document.getElementById('app')! if (!rootElement.innerHTML) { const root = ReactDOM.createRoot(rootElement) root.render( <StrictMode> <RouterProvider router={router} /> </StrictMode>, ) } ``` -------------------------------- ### Retaining specific search parameters with retainSearchParams Source: https://tanstack.com/router/latest/docs/api/router/retainSearchParamsFunction.md This example demonstrates how to use retainSearchParams with an array of keys to persist specific search parameters defined in a Zod schema within a root route. ```tsx import { z } from 'zod' import { createRootRoute, retainSearchParams } from '@tanstack/react-router' const searchSchema = z.object({ rootValue: z.string().optional(), }) export const Route = createRootRoute({ validateSearch: searchSchema, search: { middlewares: [retainSearchParams(['rootValue'])], }, }) ``` -------------------------------- ### Set Default Preload Strategy to Intent Source: https://tanstack.com/router/latest/docs/guide/preloading.md Configures the router to use the 'intent' preloading strategy by default for all links. This strategy preloads route dependencies based on hover and touch start events. ```tsx import { createRouter } from '@tanstack/react-router' const router = createRouter({ // ... defaultPreload: 'intent', }) ``` ```tsx import { createRouter } from '@tanstack/solid-router' const router = createRouter({ // ... defaultPreload: 'intent', }) ``` -------------------------------- ### Implementing CatchBoundary with Error Handling and Reset Source: https://tanstack.com/router/latest/docs/api/router/catchBoundaryComponent.md This example demonstrates how to use the CatchBoundary component to catch errors from its children. It includes an `onCatch` callback to log the error and a `getResetKey` function to enable state resetting when the key changes. The component renders its children when there are no errors and the `errorComponent` when an error occurs. ```tsx import { CatchBoundary } from '@tanstack/react-router' function Component() { return ( <CatchBoundary getResetKey={() => 'reset'} onCatch={(error) => console.error(error)} > <div>My Component</div> </CatchBoundary> ) } ``` -------------------------------- ### Configure Router Context for React and Solid Source: https://tanstack.com/router/latest/docs/guide/router-context.md Sets up a typed router context for integrating external libraries like QueryClient. ```tsx import { createRootRouteWithContext, createRouter, } from '@tanstack/react-router' interface MyRouterContext { queryClient: QueryClient } const rootRoute = createRootRouteWithContext<MyRouterContext>()({ component: App, }) const queryClient = new QueryClient() const router = createRouter({ routeTree: rootRoute, context: { queryClient, }, }) ``` ```tsx import { createRootRouteWithContext, createRouter, } from '@tanstack/solid-router' interface MyRouterContext { queryClient: QueryClient } const rootRoute = createRootRouteWithContext<MyRouterContext>()({ component: App, }) const queryClient = new QueryClient() const router = createRouter({ routeTree: rootRoute, context: { queryClient, }, }) ``` -------------------------------- ### Solid Router Initialization Source: https://tanstack.com/router/latest/docs/installation/manual.md Initializes and renders the TanStack Router for a Solid application. Ensure your HTML has a root element with id 'root'. ```tsx /* @refresh reload */ import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' // Import the generated route tree import { routeTree } from './routeTree.gen' // Create a new router instance const router = createRouter({ routeTree }) // Register the router instance for type safety declare module '@tanstack/solid-router' { interface Register { router: typeof router } } // Render the app const rootElement = document.getElementById('root')! render(() => <RouterProvider router={router} />, rootElement) ``` -------------------------------- ### Initialize Router with Placeholder Context Source: https://tanstack.com/router/latest/docs/guide/router-context.md Initializes the router with a placeholder for context values that will be provided in React-land. ```tsx import { createRouter } from '@tanstack/react-router' import { routeTree } from './routeTree.gen' export const router = createRouter({ routeTree, context: { networkStrength: undefined!, // We'll set this in React-land }, }) ``` -------------------------------- ### Transform Search Params with Custom Middleware Source: https://tanstack.com/router/latest/docs/guide/search-params.md Define custom search middlewares in the `search.middlewares` array to transform search parameters before links are generated or during navigation. This example adds `rootValue` to the search params if it exists. ```tsx import { z } from 'zod' import { zodValidator } from '@tanstack/zod-adapter' const searchSchema = z.object({ rootValue: z.string().optional(), }) export const Route = createRootRoute({ validateSearch: zodValidator(searchSchema), search: { middlewares: [ ({ search, next }) => { const result = next(search) return { rootValue: search.rootValue, ...result, } }, ], }, }) ``` -------------------------------- ### SSR Dehydration/Hydration with TanStack Query Source: https://tanstack.com/router/latest/docs/guide/external-data-loading.md This example demonstrates how to configure TanStack Router with `dehydrate` and `hydrate` callbacks to serialize and deserialize a `QueryClient`'s state for SSR. This ensures that data fetched on the server is available on the client, improving initial load performance. ```tsx import { QueryClient, QueryClientProvider, dehydrate, hydrate } from '@tanstack/query-core' import { createRouter } from '@tanstack/react-router' // Assuming routeTree is defined elsewhere // import { routeTree } from './routeTree' export function createRouter() { // Make sure you create your loader client or similar data // stores inside of your `createRouter` function. This ensures // that your data stores are unique to each request and // always present on both server and client. const queryClient = new QueryClient() return createRouter({ routeTree, // Optionally provide your loaderClient to the router context for // convenience (you can provide anything you want to the router // context!) context: { queryClient, }, // On the server, dehydrate the loader client so the router // can serialize it and send it to the client for us dehydrate: () => { return { queryClientState: dehydrate(queryClient), } }, // On the client, hydrate the loader client with the data // we dehydrated on the server hydrate: (dehydrated) => { hydrate(queryClient, dehydrated.queryClientState) }, // Optionally, we can use `Wrap` to wrap our router in the loader client provider Wrap: ({ children }) => { return ( <QueryClientProvider client={queryClient}> {children} </QueryClientProvider> ) }, }) } ``` -------------------------------- ### Using useNavigate Hook for Navigation in React Source: https://tanstack.com/router/latest/docs/api/router/useNavigateHook.md Demonstrates how to use the useNavigate hook to get a navigate function for programmatic navigation. The navigate function can be called with options to change the search parameters, pathname, hash, or state, allowing for flexible route updates. ```tsx import { useNavigate } from '@tanstack/react-router' function PostsPage() { const navigate = useNavigate({ from: '/posts' }) const handleClick = () => navigate({ search: { page: 2 } }) // ... } function Component() { const navigate = useNavigate() return ( <div> <button onClick={() => navigate({ to: '/posts', }) } > Posts </button> <button onClick={() => navigate({ to: '/posts', search: { page: 2 }, }) } > Posts (Page 2) </button> <button onClick={() => navigate({ to: '/posts', hash: 'my-hash', }) } > Posts (Hash) </button> <button onClick={() => navigate({ to: '/posts', state: { from: 'home' }, }) } > Posts (State) </button> </div> ) } ``` -------------------------------- ### Subscribe to Router Events Source: https://tanstack.com/router/latest/docs/api/router/RouterEventsType.md Demonstrates how to initialize a router instance and subscribe to specific lifecycle events using the router.subscribe method. ```typescript import { createRouter } from '@tanstack/react-router' import { routeTree } from './routeTree.gen' const router = createRouter({ routeTree }) const unsub = router.subscribe('onResolved', (evt) => { // Handle the resolved event }) ``` -------------------------------- ### Manual Scroll Restoration for Window Virtualization (React) Source: https://tanstack.com/router/latest/docs/guide/scroll-restoration.md Manually controls scroll restoration for virtualized lists within the entire browser window. It uses `useElementScrollRestoration` to get scroll data and passes it to `useWindowVirtualizer` for initial offset. Dependencies include TanStack Router and TanStack Virtual. ```tsx function Component() { const scrollEntry = useElementScrollRestoration({ getElement: () => window, }) const virtualizer = useWindowVirtualizer({ count: 10000, estimateSize: () => 100, initialOffset: scrollEntry?.scrollY, }) return ( <div> {virtualizer.getVirtualItems().map(item => ( ... ))} </div> ) } ``` -------------------------------- ### Instantiate Router Instance with React Source: https://tanstack.com/router/latest/docs/api/router/RouterClass.md Demonstrates how to instantiate a new router instance using the deprecated `Router` class and integrate it with `RouterProvider` in a React application. It configures the router with a route tree and a default preload strategy. ```tsx import { Router, RouterProvider } from '@tanstack/react-router' import { routeTree } from './routeTree.gen' const router = new Router({ routeTree, defaultPreload: 'intent', }) export default function App() { return <RouterProvider router={router} /> } ``` -------------------------------- ### Create a basic custom link component Source: https://tanstack.com/router/latest/docs/guide/custom-link.md Demonstrates how to use createLink to wrap a standard anchor element in React and Solid, providing consistent styling and preloading behavior. ```tsx import * as React from 'react' import { createLink, LinkComponent } from '@tanstack/react-router' interface BasicLinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {} const BasicLinkComponent = React.forwardRef<HTMLAnchorElement, BasicLinkProps>((props, ref) => { return <a ref={ref} {...props} className={'block px-3 py-2 text-blue-700'} /> }) const CreatedLinkComponent = createLink(BasicLinkComponent) export const CustomLink: LinkComponent<typeof BasicLinkComponent> = (props) => { return <CreatedLinkComponent preload={'intent'} {...props} /> } ``` ```tsx import * as Solid from 'solid-js' import { createLink, LinkComponent } from '@tanstack/solid-router' type BasicLinkProps = Solid.JSX.IntrinsicElements['a'] & {} const BasicLinkComponent: Solid.Component<BasicLinkProps> = (props) => ( <a {...props} class="block px-3 py-2 text-red-700">{props.children}</a> ) const CreatedLinkComponent = createLink(BasicLinkComponent) export const CustomLink: LinkComponent<typeof BasicLinkComponent> = (props) => { return <CreatedLinkComponent preload={'intent'} {...props} /> } ``` -------------------------------- ### Zod v4 Direct Schema Validation Source: https://tanstack.com/router/latest/docs/guide/search-params.md For Zod v4, directly use the Zod schema in `validateSearch` without an adapter. This simplifies the setup and maintains type inference. ```tsx import { z } from 'zod' const productSearchSchema = z.object({ page: z.number().default(1), filter: z.string().default(''), sort: z.enum(['newest', 'oldest', 'price']).default('newest'), }) export const Route = createFileRoute('/shop/products/')({ // With Zod v4, we can use the schema without the adapter validateSearch: productSearchSchema, }) ``` -------------------------------- ### Create Root Route with Context in Solid Source: https://tanstack.com/router/latest/docs/guide/data-loading.md Use `createRootRouteWithContext` to define a root route and provide typed context for your router. Note the double call `()()` which is intentional. ```tsx import { createRootRouteWithContext } from '@tanstack/solid-router' // Create a root route using the createRootRouteWithContext<{...}>() function and pass it whatever types you would like to be available in your router context. export const Route = createRootRouteWithContext<{ fetchPosts: typeof fetchPosts }>()() // NOTE: the double call is on purpose, since createRootRouteWithContext is a factory ;) ``` -------------------------------- ### Accessing Route Context with useRouteContext (React) Source: https://tanstack.com/router/latest/docs/api/router/useRouteContextHook.md Demonstrates how to use the useRouteContext hook in React components to retrieve the current route's context. It shows examples of accessing the full context and selecting specific properties using the 'select' option. ```tsx import { useRouteContext } from '@tanstack/react-router' function Component() { const context = useRouteContext({ from: '/posts/$postId' }) // ^ RouteContext // OR const selected = useRouteContext({ from: '/posts/$postId', select: (context) => context.postId, }) // ^ string // ... } ``` -------------------------------- ### Immediate Navigation with Navigate Component Source: https://tanstack.com/router/latest/docs/guide/navigation.md Render the `Navigate` component to navigate immediately when a component mounts. This is useful for client-only redirects. ```tsx function Component() { return <Navigate to="/posts/$postId" params={{ postId: 'my-first-post' }} /> } ``` -------------------------------- ### ArkType Standard Schema Validation Source: https://tanstack.com/router/latest/docs/guide/search-params.md Integrate ArkType schemas directly into `validateSearch` without an adapter, as ArkType implements Standard Schema. Ensure the `arktype` 2.0-rc package is installed. ```tsx import { type } from 'arktype' const productSearchSchema = type({ page: 'number = 1', filter: 'string = ""', sort: '"newest" | "oldest" | "price" = "newest"', }) export const Route = createFileRoute('/shop/products/')({ validateSearch: productSearchSchema, }) ``` -------------------------------- ### Router Configuration Source: https://tanstack.com/router/latest/docs/guide/render-optimizations.md Configuring global router options for performance optimizations. ```APIDOC ## POST createRouter ### Description Initializes the router instance with global configuration options, including default structural sharing behavior. ### Method FUNCTION ### Parameters #### Options - **routeTree** (RouteTree) - Required - The defined route tree. - **defaultStructuralSharing** (boolean) - Optional - Globally enables or disables structural sharing for all select hooks. ``` -------------------------------- ### Valibot Standard Schema Validation Source: https://tanstack.com/router/latest/docs/guide/search-params.md Use Valibot schemas directly in `validateSearch` without an adapter, as Valibot implements Standard Schema. Ensure the `valibot` 1.0 package is installed. ```tsx import * as v from 'valibot' const productSearchSchema = v.object({ page: v.optional(v.fallback(v.number(), 1), 1), filter: v.optional(v.fallback(v.string(), ''), ''), sort: v.optional( v.fallback(v.picklist(['newest', 'oldest', 'price']), 'newest'), 'newest', ), }) export const Route = createFileRoute('/shop/products/')({ validateSearch: productSearchSchema, }) ``` -------------------------------- ### Using useAwaited to resolve deferred promises Source: https://tanstack.com/router/latest/docs/api/router/useAwaitedHook.md This example demonstrates how to use the useAwaited hook within a React component to await a deferred promise provided by the router's loader data. It ensures the component suspends until the data is available. ```tsx import { useAwaited } from '@tanstack/react-router' function Component() { const { deferredPromise } = route.useLoaderData() const data = useAwaited({ promise: myDeferredPromise }) // ... } ``` -------------------------------- ### Configure Supabase Environment Variables Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Sets up environment variables for Supabase URL and Anon Key in a `.env` file. These are required for the Supabase client to connect to your project. ```env VITE_SUPABASE_URL=https://your-project.supabase.co VITE_SUPABASE_ANON_KEY=your_supabase_anon_key ``` -------------------------------- ### Link Component with Intent-Based Preloading Source: https://tanstack.com/router/latest/docs/guide/navigation.md Demonstrates how to enable automatic route preloading on user intent (hover or touchstart) by passing the `preload='intent'` prop to the Link component. ```tsx const link = ( <Link to="/blog/post/$postId" preload="intent"> Blog Post </Link> ) ``` -------------------------------- ### Run DOM-Dependent Logic with onRendered (TypeScript/React) Source: https://tanstack.com/router/latest/docs/guide/router-events.md This example demonstrates using the 'onRendered' event to execute logic that depends on the DOM. It subscribes to 'onRendered' and calls a function to focus the page heading based on the new route's pathname. ```tsx const unsubscribe = router.subscribe('onRendered', ({ toLocation }) => { focusPageHeading(toLocation.pathname) }) ``` -------------------------------- ### Default Configuration for Solid Projects Source: https://tanstack.com/router/latest/docs/installation/with-router-cli.md Default configuration options for TanStack Router CLI when targeting Solid projects. ```json { "routesDirectory": "./src/routes", "generatedRouteTree": "./src/routeTree.gen.ts", "routeFileIgnorePrefix": "-", "quoteStyle": "single", "target": "solid" } ``` -------------------------------- ### Create Lazy File Route Instance - React Source: https://tanstack.com/router/latest/docs/api/router/createLazyFileRouteFunction.md Demonstrates how to use the createLazyFileRoute function to define a lazily loaded route component for the root path in a React application using TanStack Router. This setup allows for code splitting and efficient loading of route components. ```tsx import { createLazyFileRoute } from '@tanstack/react-router' export const Route = createLazyFileRoute('/')({ component: IndexComponent, }) function IndexComponent() { const data = Route.useLoaderData() return <div>{data}</div> } ``` -------------------------------- ### Auth0 Environment Variables Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Configure your Auth0 domain and client ID in your .env file. These are required for the Auth0Provider. ```env VITE_AUTH0_DOMAIN=your-auth0-domain.auth0.com VITE_AUTH0_CLIENT_ID=your_auth0_client_id ``` -------------------------------- ### Code-Splitting Data Loaders with lazyFn Source: https://tanstack.com/router/latest/docs/guide/code-splitting.md Illustrates how to code-split data loading logic for routes using the Route's loader option and the lazyFn utility. This can reduce bundle size but may impact type-safety. ```tsx import { lazyFn } from '@tanstack/react-router' const route = createRoute({ path: '/my-route', component: MyComponent, loader: lazyFn(() => import('./loader'), 'loader'), }) // In another file... export const loader = async (context: LoaderContext) => { /// ... } ``` ```tsx import { lazyFn } from '@tanstack/solid-router' const route = createRoute({ path: '/my-route', component: MyComponent, loader: lazyFn(() => import('./loader'), 'loader'), }) // In another file... export const loader = async (context: LoaderContext) => { /// ... } ``` -------------------------------- ### Programmatic Navigation Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Shows how to perform programmatic navigation using `navigate()` or `router.navigate()`, which also respects URL rewrites. ```APIDOC ## Programmatic Navigation Programmatic navigation via `navigate()` or `router.navigate()` also respects rewrites: ### Request Example ```tsx const navigate = useNavigate() // Navigates to /about internally, displays /en/about in browser navigate({ to: '/about' }) ``` ``` -------------------------------- ### Manually Preload a Route (React, Solid) Source: https://tanstack.com/router/latest/docs/guide/preloading.md Demonstrates how to use the router's `preloadRoute` method to manually preload a specific route. This method accepts navigation options and returns a promise that resolves upon successful preloading. Error handling for preload failures is included. ```tsx import { useEffect } from 'react' import { useRouter } from '@tanstack/react-router' function Component() { const router = useRouter() useEffect(() => { async function preload() { try { const matches = await router.preloadRoute({ to: postRoute, params: { id: 1 }, }) } catch (err) { // Failed to preload route } } preload() }, [router]) return <div /> } ``` ```tsx import { createEffect } from 'solid-js' import { useRouter } from '@tanstack/solid-router' function Component() { const router = useRouter() createEffect(() => { async function preload() { try { const matches = await router.preloadRoute({ to: postRoute, params: { id: 1 }, }) } catch (err) { // Failed to preload route } } preload() }) return <div /> } ``` -------------------------------- ### Create Posts Route File Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-location.md Defines the '/posts' route with a component and a loader function to fetch posts. Use this for the main posts listing page. ```tsx // src/routes/posts.tsx import { createFileRoute, Link, Outlet } from '@tanstack/react-router' export const Route = createFileRoute('/posts')({ component: Posts, loader: async () => { const posts = await fetchPosts() return { posts, } }, }) function Posts() { const { posts } = Route.useLoaderData() return ( <div> <nav> {posts.map((post) => ( <Link key={post.id} to={`/posts/$postId`} params={{ postId: post.id }} > {post.title} </Link> ))} </nav> <Outlet /> </div> ) } ``` -------------------------------- ### Handle Validation Errors with Zod Source: https://tanstack.com/router/latest/docs/guide/search-params.md Configure `onError` to handle search param validation errors by rendering an `errorComponent`. This example uses Zod's `.default()` to trigger an error when parameters are malformed. ```typescript import { z } from 'zod' const productSearchSchema = z.object({ page: z.number().default(1), filter: z.string().default(''), sort: z.enum(['newest', 'oldest', 'price']).default('newest'), }) export const Route = createFileRoute('/shop/products/')({ validateSearch: productSearchSchema, }) ``` -------------------------------- ### i18n Locale Prefix URL Rewrite Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Strip locale prefixes from the browser URL on input and add them back on output. This example demonstrates how to handle locale prefixes like '/en/about' by removing 'en' before routing and re-adding it based on the current locale when navigating. ```tsx const locales = ['en', 'fr', 'es', 'de'] const defaultLocale = 'en' // Get current locale (from cookie, localStorage, or detection) function getLocale() { return localStorage.getItem('locale') || defaultLocale } const router = createRouter({ routeTree, rewrite: { input: ({ url }) => { // Check if pathname starts with a locale prefix const segments = url.pathname.split('/').filter(Boolean) const firstSegment = segments[0] if (firstSegment && locales.includes(firstSegment)) { // Strip the locale prefix: /en/about → /about url.pathname = '/' + segments.slice(1).join('/') || '/' } return url }, output: ({ url }) => { const locale = getLocale() // Add locale prefix: /about → /en/about if (locale !== defaultLocale || true) { // Always prefix, or conditionally skip default locale url.pathname = `/${locale}${url.pathname === '/' ? '' : url.pathname}` } return url }, }, }) ``` -------------------------------- ### Standalone redirect function usage in React Router Source: https://tanstack.com/router/latest/docs/api/router/redirectFunction.md Demonstrates how to use the standalone `redirect` function from '@tanstack/react-router' within route loader callbacks. It shows examples of redirecting to internal routes using 'to' and external URLs using 'href', as well as forcing the function to throw the redirect object. ```tsx import { redirect } from '@tanstack/react-router' const route = createRoute({ // throwing an internal redirect object using 'to' property loader: () => { if (!user) { throw redirect({ to: '/login', }) } }, // throwing an external redirect object using 'href' property loader: () => { if (needsExternalAuth) { throw redirect({ href: 'https://authprovider.com/login', }) } }, // or forcing `redirect` to throw itself loader: () => { if (!user) { redirect({ to: '/login', throw: true, }) } }, // ... other route options }) ``` -------------------------------- ### Initialize Router Context Source: https://tanstack.com/router/latest/docs/guide/router-context.md Provide the initial context object when creating the router instance. ```tsx import { createRouter } from '@tanstack/react-router' import { routeTree } from './routeTree.gen' const router = createRouter({ routeTree, context: { foo: true, }, }) ``` ```tsx import { createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' const router = createRouter({ routeTree, context: { foo: true, }, }) ``` -------------------------------- ### Solid: Query-String Library for Search Param Serialization Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md Shows how to integrate the 'query-string' library with TanStack Router in SolidJS for robust search parameter parsing and stringification. This ensures consistent query string handling. ```tsx import { createRouter } from '@tanstack/solid-router' import qs from 'query-string' const router = createRouter({ // ... stringifySearch: stringifySearchWith((value) => qs.stringify(value, { // ...options }), ), parseSearch: parseSearchWith((value) => qs.parse(value, { // ...options }), ), }) ``` -------------------------------- ### Throwing NotFoundError in Route Loader Source: https://tanstack.com/router/latest/docs/api/router/notFoundFunction.md Demonstrates how to use the notFound function within a route's loader callback to throw a NotFoundError. This can be used to conditionally display a 'not found' component based on data availability or other conditions. The example shows throwing a basic notFound object and another with a specified routeId. ```tsx import { notFound, createFileRoute, rootRouteId } from '@tanstack/react-router' const Route = new createFileRoute('/posts/$postId')({ // throwing a not-found object loader: ({ context: { post } }) => { if (!post) { throw notFound() } }, // or if you want to show a not-found on the whole page loader: ({ context: { team } }) => { if (!team) { throw notFound({ routeId: rootRouteId }) } }, // ... other route options }) ``` -------------------------------- ### Navigate with Path Params (Function Style) Source: https://tanstack.com/router/latest/docs/guide/path-params.md Illustrates navigating to a route with path parameters using a function for the `params` prop. This allows for merging existing params with new ones. ```tsx function Component() { return ( <Link to="/blog/$postId" params={(prev) => ({ ...prev, postId: '123' })}> Post 123 </Link> ) } ``` -------------------------------- ### Manual Scroll Restoration for Specific Elements (React & Solid) Source: https://tanstack.com/router/latest/docs/guide/scroll-restoration.md Manually controls scroll restoration for a specific element, such as a virtualized list container. It requires a unique `scrollRestorationId` and uses the `data-scroll-restoration-id` attribute on the target element. The `useElementScrollRestoration` hook provides scroll data, which is then passed to the virtualizer's `initialOffset`. This example demonstrates implementations in both React and Solid. ```tsx function Component() { const scrollRestorationId = 'myVirtualizedContent' const scrollEntry = useElementScrollRestoration({ id: scrollRestorationId, }) const virtualizerParentRef = React.useRef<HTMLDivElement>(null) const virtualizer = useVirtualizer({ count: 10000, getScrollElement: () => virtualizerParentRef.current, estimateSize: () => 100, initialOffset: scrollEntry?.scrollY, }) return ( <div ref={virtualizerParentRef} data-scroll-restoration-id={scrollRestorationId} className="flex-1 border rounded-lg overflow-auto relative" > ... </div> ) } ``` ```tsx function Component() { const scrollRestorationId = 'myVirtualizedContent' const scrollEntry = useElementScrollRestoration({ id: scrollRestorationId, }) let virtualizerParentRef: any const virtualizer = createVirtualizer({ count: 10000, getScrollElement: () => virtualizerParentRef, estimateSize: () => 100, initialOffset: scrollEntry?.scrollY, }) return ( <div ref={virtualizerParentRef} data-scroll-restoration-id={scrollRestorationId} class="flex-1 border rounded-lg overflow-auto relative" > ... </div> ) } ``` -------------------------------- ### Define Solid Routes with Code Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md Use `createRootRoute` and `createRoute` to define your application's route tree in code for Solid. This approach mirrors file-based routing structure but is defined programmatically. ```tsx import { createRootRoute, createRoute } from '@tanstack/solid-router' const rootRoute = createRootRoute() const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', }) const aboutRoute = createRoute({ getParentRoute: () => rootRoute, path: 'about', }) const postsRoute = createRoute({ getParentRoute: () => rootRoute, path: 'posts', }) const postsIndexRoute = createRoute({ getParentRoute: () => postsRoute, path: '/', }) const postRoute = createRoute({ getParentRoute: () => postsRoute, path: '$postId', }) const postEditorRoute = createRoute({ getParentRoute: () => rootRoute, path: 'posts/$postId/edit', }) const settingsRoute = createRoute({ getParentRoute: () => rootRoute, path: 'settings', }) const profileRoute = createRoute({ getParentRoute: () => settingsRoute, path: 'profile', }) const notificationsRoute = createRoute({ getParentRoute: () => settingsRoute, path: 'notifications', }) const pathlessLayoutRoute = createRoute({ getParentRoute: () => rootRoute, id: 'pathlessLayout', }) const pathlessLayoutARoute = createRoute({ getParentRoute: () => pathlessLayoutRoute, path: 'route-a', }) const pathlessLayoutBRoute = createRoute({ getParentRoute: () => pathlessLayoutRoute, path: 'route-b', }) const filesRoute = createRoute({ getParentRoute: () => rootRoute, path: 'files/$', }) ``` -------------------------------- ### Execute Inline Scripts Before Hydration with ScriptOnce Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md ScriptOnce allows for the execution of JavaScript before the framework hydrates. This is ideal for theme detection to avoid flashes of unstyled content. ```tsx import { ScriptOnce } from '@tanstack/react-router' const themeScript = `(function() { try { const theme = localStorage.getItem('theme') || 'auto'; const resolved = theme === 'auto' ? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') : theme; document.documentElement.classList.add(resolved); } catch (e) {} })();` function ThemeProvider({ children }) { return ( <> <ScriptOnce children={themeScript} /> {children} </> ) } ``` ```tsx import { ScriptOnce } from '@tanstack/solid-router' const themeScript = `(function() { try { const theme = localStorage.getItem('theme') || 'auto'; const resolved = theme === 'auto' ? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') : theme; document.documentElement.classList.add(resolved); } catch (e) {} })();` function ThemeProvider({ children }) { return ( <> <ScriptOnce children={themeScript} /> {children} </> ) } ``` -------------------------------- ### Navigate with Prefix and Suffix Optional Parameters Source: https://tanstack.com/router/latest/docs/guide/navigation.md Use optional parameters with prefix or suffix syntax in the 'to' path. Set the parameter to undefined to omit it during navigation. ```tsx // Navigate to file with optional name <Link to="/files/prefix{-$name}.txt" params={{ name: 'document' }} > Document File </Link> // Navigate to file without optional name <Link to="/files/prefix{-$name}.txt" params={{ name: undefined }} > Default File </Link> ``` -------------------------------- ### Create root route with context Source: https://tanstack.com/router/latest/docs/guide/data-loading.md Initialize the root route with a typed context for dependency injection. ```tsx import { createRootRouteWithContext } from '@tanstack/react-router' // Create a root route using the createRootRouteWithContext<{...}>() function and pass it whatever types you would like to be available in your router context. export const Route = createRootRouteWithContext<{ fetchPosts: typeof fetchPosts }>()() // NOTE: the double call is on purpose, since createRootRouteWithContext is a factory ;) ``` -------------------------------- ### createRoute Function Usage Source: https://tanstack.com/router/latest/docs/api/router/createRouteFunction.md Demonstrates how to use the createRoute function to define a root route with a path, loader, and component. ```APIDOC ## createRoute Function The `createRoute` function returns a `Route` instance that can be used to build a route tree for the router. ### Method `createRoute(options)` ### Parameters #### Request Body - **options** (`RouteOptions`) - Required - The options used to configure the route instance. - **getParentRoute** (`() => Route`) - Required - A function that returns the parent route. - **path** (`string`) - Required - The path for the route. - **loader** (`() => Promise<TData> | TData`) - Optional - A function that loads data for the route. - **component** (`React.ComponentType`) - Optional - The React component to render for the route. ### Response #### Success Response (200) - **Route** (`Route`) - A new `Route` instance. ### Request Example ```tsx import { createRoute } from '@tanstack/react-router' import { rootRoute } from './__root' const Route = createRoute({ getParentRoute: () => rootRoute, path: '/', loader: () => { return 'Hello World' }, component: IndexComponent, }) function IndexComponent() { const data = Route.useLoaderData() return <div>{data}</div> } ``` ``` -------------------------------- ### Optimize Permission Checks with Memoization Source: https://tanstack.com/router/latest/docs/how-to/setup-rbac.md Use useMemo to cache permission results and prevent unnecessary re-computations during renders. ```tsx import { useMemo } from 'react' function usePermissions() { const { auth } = Route.useRouteContext() const permissions = useMemo( () => ({ canEditUsers: auth.hasPermission('users:write'), canDeleteUsers: auth.hasPermission('users:delete'), isAdmin: auth.hasRole('admin'), isModerator: auth.hasAnyRole(['admin', 'moderator']), }), [auth.user?.roles, auth.user?.permissions], ) return permissions } ``` -------------------------------- ### Create Routes Directory Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-location.md Create the 'routes' directory within the 'src' directory to house your route files. ```sh mkdir src/routes ``` -------------------------------- ### Import Path Extensions Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md Configure how file extensions are handled in import paths within the generated route tree. ```APIDOC ### `addExtensions` - Type: `boolean | string` - Default: `false` This option controls file extensions on import paths in the generated route tree. - `false` — Extensions are stripped from import paths (e.g. `'./routes/posts'`) - `true` — The original file extensions are kept (e.g. `'./routes/posts.tsx'`) - `string` — The original extension is replaced with the provided one (e.g. `'js'` produces `'./routes/posts.js'`) Passing a string is useful when your project uses ESM, since Node.js ESM requires `.js` extensions for imports even when the source files are `.ts` or `.tsx`. ```ts // Example: replace .tsx/.ts extensions with .js in generated imports TanStackRouterVite({ addExtensions: 'js', }) ``` ``` -------------------------------- ### Create Route Mask in SolidJS with TanStack Router Source: https://tanstack.com/router/latest/docs/guide/route-masking.md Demonstrates how to create a route mask using `createRouteMask` from `@tanstack/solid-router`. This involves defining the `routeTree`, the `from` route, and mapping parameters to the `to` route. The created mask is then passed to the router configuration. ```tsx import { createRouteMask } from '@tanstack/solid-router' const photoModalToPhotoMask = createRouteMask({ routeTree, from: '/photos/$photoId/modal', to: '/photos/$photoId', params: (prev) => ({ photoId: prev.photoId, }), }) const router = createRouter({ routeTree, routeMasks: [photoModalToPhotoMask], }) ``` -------------------------------- ### Configure Babel for Solid Source: https://tanstack.com/router/latest/docs/installation/with-webpack.md Include the required presets in your .babelrc file when using Solid with Webpack. ```tsx // .babelrc { "presets": ["babel-preset-solid", "@babel/preset-typescript"] } ``` -------------------------------- ### Configure package.json Scripts for CLI Source: https://tanstack.com/router/latest/docs/installation/with-router-cli.md Add scripts to your package.json to enable route generation and watching using the TanStack Router CLI. ```json { "scripts": { "generate-routes": "tsr generate", "watch-routes": "tsr watch", "build": "npm run generate-routes && ...", "dev": "npm run watch-routes && ..." } } ``` -------------------------------- ### Initial Link Options without `linkOptions` (TypeScript) Source: https://tanstack.com/router/latest/docs/guide/link-options.md Illustrates a basic approach to defining link options as an object literal. This method has potential type-checking issues, as properties like `to` might be inferred too broadly, and type errors might only be caught when the options are spread into a `Link` component, rather than during the option definition itself. ```tsx const dashboardLinkOptions = { to: '/dashboard', search: { search: '' }, } function DashboardComponent() { return <Link {...dashboardLinkOptions} /> } ``` -------------------------------- ### Route matching process for /blog Source: https://tanstack.com/router/latest/docs/routing/route-matching.md Visual representation of the matching process for the /blog URL. ```text Root ❌ / ❌ about/us ❌ about ⏩ blog ✅ / - new - $postId - * ``` -------------------------------- ### Create Array of Reusable Link Options with `linkOptions` (TypeScript) Source: https://tanstack.com/router/latest/docs/guide/link-options.md Shows how to use `linkOptions` to type-check an array of navigation options, suitable for generating navigation bars or lists. Each object in the array is individually type-checked, ensuring that all navigation items are correctly defined. This is useful for scenarios where you need to loop over options to render multiple links. ```tsx const options = linkOptions([ { to: '/dashboard', label: 'Summary', activeOptions: { exact: true }, }, { to: '/dashboard/invoices', label: 'Invoices', }, { to: '/dashboard/users', label: 'Users', }, ]) function DashboardComponent() { return ( <> <div className="flex items-center border-b"> <h2 className="text-xl p-2">Dashboard</h2> </div> <div className="flex flex-wrap divide-x"> {options.map((option) => { return ( <Link {...option} key={option.to} activeProps={{ className: `font-bold` }} className="p-2" > {option.label} </Link> ) })} </div> <hr /> <Outlet /> </> ) } ``` -------------------------------- ### Navigate Component Source: https://tanstack.com/router/latest/docs/guide/navigation.md A component that triggers navigation immediately upon mounting, useful for client-side redirects. ```APIDOC ## <Navigate /> ### Description Navigates to a specified route immediately when the component mounts. ### Parameters - **to** (string) - Required - The destination path. - **params** (object) - Optional - Route parameters for the destination. ``` -------------------------------- ### Subdomain to Path Routing with Rewrites Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Route subdomain requests to path-based routes and reverse the transformation for link generation. Handles `admin.example.com` and `api.example.com`. ```tsx const router = createRouter({ routeTree, rewrite: { input: ({ url }) => { const subdomain = url.hostname.split('.')[0] // admin.example.com/users → /admin/users if (subdomain === 'admin') { url.pathname = '/admin' + url.pathname } // api.example.com/v1/users → /api/v1/users else if (subdomain === 'api') { url.pathname = '/api' + url.pathname } return url }, output: ({ url }) => { // Reverse the transformation for link generation if (url.pathname.startsWith('/admin')) { url.hostname = 'admin.example.com' url.pathname = url.pathname.replace(/^\/admin/, '') || '/' } else if (url.pathname.startsWith('/api')) { url.hostname = 'api.example.com' url.pathname = url.pathname.replace(/^\/api/, '') || '/' } return url }, }, }) ``` -------------------------------- ### Legacy URL Migration with Rewrites Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Support old URLs by mapping them to new route structures. No output rewrite is needed as new URLs will be used going forward. ```tsx const legacyPaths: Record<string, string> = { '/old-about': '/about', '/old-contact': '/contact', '/blog-posts': '/blog', '/user-profile': '/account/profile', } const router = createRouter({ routeTree, rewrite: { input: ({ url }) => { const newPath = legacyPaths[url.pathname] if (newPath) { url.pathname = newPath } return url }, // No output rewrite needed - new URLs will be used going forward }, }) ``` -------------------------------- ### Create Posts Index Route File Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-location.md Defines the index route for '/posts/', typically used for the default view when navigating to the posts directory. Ensure this file is named `posts.index.tsx`. ```tsx // src/routes/posts.index.tsx import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/posts/')({ component: PostsIndex, }) ``` -------------------------------- ### Using defer with TanStack Router loaders and components Source: https://tanstack.com/router/latest/docs/api/router/deferFunction.md Demonstrates how to wrap a fetch promise using defer within a route loader and consume it using either the useAwaited hook or the Await component in a React component. ```tsx import { defer } from '@tanstack/react-router' const route = createRoute({ loader: () => { const deferredPromise = defer(fetch('/api/data')) return { deferredPromise } }, component: MyComponent, }) function MyComponent() { const { deferredPromise } = Route.useLoaderData() const data = useAwaited({ promise: deferredPromise }) // or return ( <Await promise={deferredPromise}> {(data) => <div>{JSON.stringify(data)}</div>} </Await> ) } ``` -------------------------------- ### Get Current Location with useLocation Hook (React) Source: https://tanstack.com/router/latest/docs/api/router/useLocationHook.md The useLocation hook from TanStack Router returns the current location object. It can optionally take a select function to return a specific property of the location, such as the pathname. This is useful for accessing routing information within React components. ```tsx import { useLocation } from '@tanstack/react-router' function Component() { const location = useLocation() // ^ ParsedLocation // OR const pathname = useLocation({ select: (location) => location.pathname, }) // ^ string // ... } ``` -------------------------------- ### Route matching process for /blog/my-post Source: https://tanstack.com/router/latest/docs/routing/route-matching.md Visual representation of the matching process for the /blog/my-post URL. ```text Root ❌ / ❌ about/us ❌ about ⏩ blog ❌ / ❌ new ✅ $postId - * ``` -------------------------------- ### Create a Root Route with Context (Solid) Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md Define a root route with custom context for Solid applications, specifying the type of the context object. ```tsx // Root route with Context import { createRootRouteWithContext } from '@tanstack/solid-router' import type { QueryClient } from '@tanstack/solid-query' export interface MyRouterContext { queryClient: QueryClient } const rootRoute = createRootRouteWithContext<MyRouterContext>() ``` -------------------------------- ### Deferred Loading with External Libraries (Solid) Source: https://tanstack.com/router/latest/docs/guide/deferred-data-loading.md This Solid.js snippet illustrates deferred data loading using an external library such as TanStack Query. The route loader triggers data fetching using library-specific functions (`prefetchQuery`, `ensureQueryData`). Components then retrieve this data using the library's hooks, enabling the router to render the route before all background data is fully resolved and cached. ```tsx import { createFileRoute } from '@tanstack/solid-router' import { slowDataOptions, fastDataOptions } from '~/api/query-options' export const Route = createFileRoute('/posts/$postId')({ loader: async ({ context: { queryClient } }) => { // Kick off the fetching of some slower data, but do not await it queryClient.prefetchQuery(slowDataOptions()) // Fetch and await some data that resolves quickly await queryClient.ensureQueryData(fastDataOptions()) }, }) ``` -------------------------------- ### Hydrate Application on Client Source: https://tanstack.com/router/latest/docs/guide/ssr.md Initializes the router and hydrates the application on the client side. ```tsx import { hydrateRoot } from 'react-dom/client' import { RouterClient } from '@tanstack/react-router/ssr/client' import { createRouter } from './router' const router = createRouter() hydrateRoot(document, <RouterClient router={router} />) ``` ```tsx import { hydrate } from 'solid-js/web' import { RouterClient } from '@tanstack/solid-router/ssr/client' import { createRouter } from './router' const router = createRouter() hydrate(() => <RouterClient router={router} />, document.body) ``` -------------------------------- ### Dynamic Post Route with Data Fetching (Solid) Source: https://tanstack.com/router/latest/docs/guide/deferred-data-loading.md This SolidJS code defines a dynamic route for individual posts using TanStack Router. It uses `useSuspenseQuery` from `@tanstack/solid-query` for asynchronous data fetching. The component manages loading states with Suspense and renders deferred data, with Solid-specific reactivity for data access. ```tsx import { createFileRoute } from '@tanstack/solid-router' import { useSuspenseQuery } from '@tanstack/solid-query' import { slowDataOptions, fastDataOptions } from '~/api/query-options' export const Route = createFileRoute('/posts/$postId')({ // ... component: PostIdComponent, }) function PostIdComponent() { const fastData = useSuspenseQuery(fastDataOptions()) // do something with fastData return ( <Suspense fallback={<div>Loading...</div>}> <SlowDataComponent /> </Suspense> ) } function SlowDataComponent() { const data = useSuspenseQuery(slowDataOptions()) return <div>{data()}</div> } ``` -------------------------------- ### Configure routeTreeFileHeader Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md Displays the default configuration for prepending content to the generated route tree file, typically used for disabling linters and type checkers. ```json [ "/* eslint-disable */", "// @ts-nocheck", "// noinspection JSUnusedGlobalSymbols" ] ``` -------------------------------- ### NotFoundRoute Class Configuration Source: https://tanstack.com/router/latest/docs/api/router/NotFoundRouteClass.md Documentation for the constructor and usage of the NotFoundRoute class. ```APIDOC ## NotFoundRoute Class ### Description Creates a not-found/404 route instance to be used in router configuration. Note: This class is deprecated; use `notFoundComponent` instead. ### Constructor Options - **options** (RouteOptions) - Required - An object containing route configuration excluding path, id, getParentRoute, caseSensitive, parseParams, and stringifyParams. ### Usage Example ```tsx import { NotFoundRoute, createRouter } from '@tanstack/react-router' import { Route as rootRoute } from './routes/__root' import { routeTree } from './routeTree.gen' const notFoundRoute = new NotFoundRoute({ getParentRoute: () => rootRoute, component: () => <div>Not found!!!</div>, }) const router = createRouter({ routeTree, notFoundRoute, }) ``` ``` -------------------------------- ### Solid Route Definition with Optional Locale Parameter Source: https://tanstack.com/router/latest/docs/guide/path-params.md Sets up a route with an optional locale parameter '/{-$locale}/' in Solid. This enables flexible URLs like '/', '/en', or '/fr'. It shows how to access route parameters and apply directionality based on the locale. ```tsx // Route structure: // routes/ // -{$locale}/ // index.tsx // /, /en, /fr // about.tsx // /about, /en/about, /fr/about // blog/ // index.tsx // /blog, /en/blog, /fr/blog // $slug.tsx // /blog/post, /en/blog/post, /fr/blog/post // routes/{-$locale}/index.tsx export const Route = createFileRoute('/{-$locale}/')({ component: HomeComponent, }) function HomeComponent() { const params = Route.useParams() const isRTL = ['ar', 'he', 'fa'].includes(params().locale || '') return ( <div dir={isRTL ? 'rtl' : 'ltr'}> <h1>Welcome ({params().locale || 'en'})</h1> {/* Localized content */} </div> ) } // routes/{-$locale}/about.tsx export const Route = createFileRoute('/{-$locale}/about')({ component: AboutComponent, }) ``` -------------------------------- ### Configure URL Rewrites for Router Paths Source: https://tanstack.com/router/latest/docs/api/router/RouterOptionsType.md Shows how to implement bidirectional URL transformation using the rewrite property to handle path prefixes like locales. ```typescript import { createRouter } from '@tanstack/react-router'; const router = createRouter({ routeTree, rewrite: { input: ({ url }) => { if (url.pathname.startsWith('/en')) { url.pathname = url.pathname.replace(/^\/en/, '') || '/'; } return url; }, output: ({ url }) => { url.pathname = `/en${url.pathname === '/' ? '' : url.pathname}`; return url; }, }, }); ``` -------------------------------- ### Customizing Layout Route Tokens with Regex Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md Demonstrates how to configure the `routeToken` option to identify layout route files using regular expressions. This allows for more flexible naming conventions for layout files beyond a simple string match. The regex is matched against the entire final segment of the route path. ```json { "routeToken": { "regex": "[a-z]+-layout", "flags": "i" } } ``` ```ts { routeToken: /[a-z]+-layout/i } ``` -------------------------------- ### Route matching process for / Source: https://tanstack.com/router/latest/docs/routing/route-matching.md Visual representation of the matching process for the root URL. ```text Root ✅ / - about/us - about - blog - / - new - $postId - * ``` -------------------------------- ### Define User Management Route with Permissions Source: https://tanstack.com/router/latest/docs/how-to/setup-rbac.md Uses createFileRoute to define a route with a beforeLoad hook for permission validation and a component that conditionally renders actions based on auth context. ```tsx import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/_authenticated/_users/manage')({ beforeLoad: ({ context }) => { // Additional permission check at the page level if (!context.auth.hasPermission('users:write')) { throw new Error('You need write permissions to manage users') } }, component: UserManagement, }) function UserManagement() { const { auth } = Route.useRouteContext() const canEdit = auth.hasPermission('users:write') const canDelete = auth.hasPermission('users:delete') return ( <div className="p-6"> <h1 className="text-3xl font-bold mb-6">User Management</h1> <div className="bg-white rounded-lg shadow overflow-hidden"> <table className="min-w-full"> <thead className="bg-gray-50"> <tr> <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase"> Name </th> <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase"> Email </th> <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase"> Role </th> <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase"> Actions </th> </tr> </thead> <tbody className="divide-y divide-gray-200"> <tr> <td className="px-6 py-4 whitespace-nowrap">John Doe</td> <td className="px-6 py-4 whitespace-nowrap">john@example.com</td> <td className="px-6 py-4 whitespace-nowrap"> <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800"> User </span> </td> <td className="px-6 py-4 whitespace-nowrap text-sm"> {canEdit && ( <button className="text-blue-600 hover:text-blue-900 mr-4"> Edit </button> )} {canDelete && ( <button className="text-red-600 hover:text-red-900"> Delete </button> )} </td> </tr> </tbody> </table> </div> <div className="mt-6 p-4 bg-blue-50 rounded"> <h3 className="font-semibold text-blue-800">Your Permissions:</h3> <ul className="text-blue-700 text-sm"> {auth.user?.permissions.map((permission) => ( <li key={permission}>✓ {permission}</li> ))} </ul> </div> </div> ) } ``` -------------------------------- ### createLink Integration Source: https://tanstack.com/router/latest/docs/guide/custom-link.md How to wrap third-party UI components with TanStack Router's createLink to enable navigation capabilities. ```APIDOC ## createLink Integration ### Description Use the `createLink` utility to transform standard UI components into router-aware components that support preloading and navigation. ### Usage - **MUI Link**: Wrap the component directly or via `React.forwardRef` for custom props. - **MUI Button**: Set the `component` prop to `a` and wrap with `createLink`. - **Mantine Anchor**: Use `createLink` to integrate Mantine's `Anchor` component. ### Implementation Example (MUI) ```tsx import { createLink } from '@tanstack/react-router' import { Link } from '@mui/material' export const CustomLink = createLink(Link) ``` ### Implementation Example (Mantine) ```tsx import { createLink } from '@tanstack/react-router' import { Anchor } from '@mantine/core' const CreatedLinkComponent = createLink(Anchor) ``` ``` -------------------------------- ### Code-Splitting Routes with createLazyRoute Source: https://tanstack.com/router/latest/docs/guide/code-splitting.md Demonstrates how to code-split route configurations using Route.lazy() and createLazyRoute. This involves separating route definitions into different files and dynamically importing them. ```tsx export const Route = createLazyRoute('/posts')({ component: MyComponent, }) function MyComponent() { return <div>My Component</div> } ``` ```tsx const postsRoute = createRoute({ getParentRoute: () => rootRoute, path: '/posts', }).lazy(() => import('./posts.lazy').then((d) => d.Route)) ``` -------------------------------- ### Create a Standard Root Route (React) Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md Initialize the root route for a React application using `createRootRoute` from `@tanstack/react-router`. ```tsx // Standard root route import { createRootRoute } from '@tanstack/react-router' const rootRoute = createRootRoute() ``` -------------------------------- ### Matching Routes Programmatically Source: https://tanstack.com/router/latest/docs/api/router/RouterType.md Shows how to use .matchRoutes to resolve a pathname and search parameters against the route tree. It returns an array of route matches. ```typescript const matches = router.matchRoutes('/users/123', { tab: 'profile' }); console.log(matches); ``` -------------------------------- ### Navigate Component API Source: https://tanstack.com/router/latest/docs/api/router/navigateComponent.md Documentation for the Navigate component, which handles programmatic navigation to new locations. ```APIDOC ## Navigate Component ### Description The `Navigate` component is used to navigate to a new location when rendered. It supports updates to pathname, search parameters, hash, and location state. Navigation is triggered within a `useEffect` hook. ### Props - **...options** (NavigateOptions) - Required - The navigation options defining the target location (pathname, search, hash, state, etc.). ### Returns - **null** - The component does not render any UI. ### Usage Example ```jsx import { Navigate } from '@tanstack/react-router' function MyComponent() { return <Navigate to="/dashboard" search={{ tab: 'profile' }} /> } ``` ``` -------------------------------- ### Link Component with Preloading Delay Configuration Source: https://tanstack.com/router/latest/docs/guide/navigation.md Illustrates how to customize the delay before intent-based preloading is triggered by using the `preloadDelay` prop with a specified number of milliseconds. ```tsx const link = ( <Link to="/blog/post/$postId" preload="intent" preloadDelay={100}> Blog Post </Link> ) ``` -------------------------------- ### Basic URL Rewrite Configuration Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Configure input and output URL rewrites when creating your router. The input function transforms the browser URL to the router's internal URL, and the output function transforms the router's internal URL back to the browser's URL. Both functions receive a URL object and can mutate it, return a new URL, a href string, or undefined to skip the rewrite. ```tsx import { createRouter } from '@tanstack/react-router' const router = createRouter({ routeTree, rewrite: { input: ({ url }) => { // Transform browser URL → router internal URL // Return the modified URL, a new URL, or undefined to skip return url }, output: ({ url }) => { // Transform router internal URL → browser URL // Return the modified URL, a new URL, or undefined to skip return url }, }, }) ``` -------------------------------- ### Importing from Excluded Files Source: https://tanstack.com/router/latest/docs/routing/routing-concepts.md Demonstrates importing components from files prefixed with a hyphen, which are ignored by the route generator. ```tsx import { createFileRoute } from '@tanstack/react-router' import { PostsTable } from './-posts-table' import { PostsHeader } from './-components/header' import { PostsFooter } from './-components/footer' export const Route = createFileRoute('/posts')({ loader: () => fetchPosts(), component: PostComponent, }) function PostComponent() { const posts = Route.useLoaderData() return ( <div> <PostsHeader /> <PostsTable posts={posts} /> <PostsFooter /> </div> ) } ``` ```tsx import { createFileRoute } from '@tanstack/solid-router' import { PostsTable } from './-posts-table' import { PostsHeader } from './-components/header' import { PostsFooter } from './-components/footer' export const Route = createFileRoute('/posts')({ loader: () => fetchPosts(), component: PostComponent, }) function PostComponent() { const posts = Route.useLoaderData() return ( <div> <PostsHeader /> <PostsTable posts={posts} /> <PostsFooter /> </div> ) } ``` -------------------------------- ### Route Type Properties and Methods Source: https://tanstack.com/router/latest/docs/api/router/RouteType.md An overview of the properties and methods available on a Route instance in TanStack Router. ```APIDOC ## Route Type The `Route` type is used to describe a route instance. ### `.addChildren` method - **Description**: Adds child routes to the route instance and returns the route instance (but with updated types to reflect the new children). - **Type**: `(children: Route[]) => this` ### `.update` method - **Description**: Updates the route instance with new options and returns the route instance (but with updated types to reflect the new options). It can be useful to update a route instance's options after it has been created to avoid circular type references. - **Type**: `(options: Partial<UpdatableRouteOptions>) => this` ### `.lazy` method - **Description**: Updates the route instance with a new lazy importer which will be resolved lazily when loading the route. This can be useful for code splitting. - **Type**: `(lazyImporter: () => Promise<Partial<UpdatableRouteOptions>>) => this` ### `.redirect` method - **Description**: A type-safe version of the `redirect` function that is pre-bound to the route's path. The `from` parameter is automatically set to the route's `fullPath`, enabling type-safe relative redirects. - **Type**: `(opts?: RedirectOptions) => Redirect` ### Example Usage of `.redirect` ```tsx import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/dashboard/settings')({ beforeLoad: ({ context }) => { if (!context.user) { // Type-safe redirect - 'from' is automatically '/dashboard/settings' throw Route.redirect({ to: '../login', // Relative path to sibling route }) } }, }) ``` ### ...`RouteApi` methods - All of the methods from [`RouteApi`](./RouteApiType.md) are available. ``` -------------------------------- ### Initialize RouteApi instance Source: https://tanstack.com/router/latest/docs/api/router/RouteApiClass.md Demonstrates how to instantiate the RouteApi class with a specific route ID and use its pre-bound hooks within a React component. This approach is deprecated and should be replaced by getRouteApi. ```tsx import { RouteApi } from '@tanstack/react-router' const routeApi = new RouteApi({ id: '/posts' }) export function PostsPage() { const posts = routeApi.useLoaderData() // ... } ``` -------------------------------- ### Configure Protocol Allowlist for Router Security Source: https://tanstack.com/router/latest/docs/api/router/RouterOptionsType.md Demonstrates how to define or extend the protocol allowlist to prevent XSS attacks by restricting allowed URL protocols in navigation. ```typescript import { createRouter, DEFAULT_PROTOCOL_ALLOWLIST } from '@tanstack/react-router'; // Use a custom allowlist (replaces the default) const router = createRouter({ routeTree, protocolAllowlist: ['https:', 'mailto:'], }); // Or extend the default allowlist const router = createRouter({ routeTree, protocolAllowlist: [...DEFAULT_PROTOCOL_ALLOWLIST, 'ftp:'], }); ``` -------------------------------- ### Navigate API Source: https://tanstack.com/router/latest/docs/api/router/RouterType.md Navigates to a new location using the provided options. ```APIDOC ## navigate Method ### Description Navigates to a new location. ### Method `navigate` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (NavigateOptions) - Required - The options for navigation. ### Request Example ```json { "to": "/dashboard", "params": { "userId": "123" } } ``` ### Response #### Success Response (200) This method returns a Promise that resolves when navigation is complete. #### Response Example ```json null ``` ``` -------------------------------- ### Implement Base64 Search Serialization Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md Demonstrates how to customize search parameter serialization using Base64 encoding to improve URL compatibility. This requires custom binary encoding and decoding functions. ```tsx import { Router, parseSearchWith, stringifySearchWith } from '@tanstack/react-router'; const router = createRouter({ parseSearch: parseSearchWith((value) => JSON.parse(decodeFromBinary(value))), stringifySearch: stringifySearchWith((value) => encodeToBinary(JSON.stringify(value))), }); function decodeFromBinary(str: string): string { return decodeURIComponent(Array.prototype.map.call(atob(str), function (c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); } function encodeToBinary(str: string): string { return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) { return String.fromCharCode(parseInt(p1, 16)); })); } ``` -------------------------------- ### Create Reusable Link Options with `linkOptions` (TypeScript) Source: https://tanstack.com/router/latest/docs/guide/link-options.md Demonstrates using the `linkOptions` function to create type-safe, reusable navigation options. This function eagerly type-checks the provided object literal, ensuring it conforms to expected link properties before it's used in components like `Link`, `navigate`, or `redirect`. It improves maintainability by catching type errors early. ```tsx const dashboardLinkOptions = linkOptions({ to: '/dashboard', search: { search: '' }, }) function DashboardComponent() { const navigate = useNavigate() return ( <div> {/** can be used in navigate ** /} <button onClick={() => navigate(dashboardLinkOptions)} /> {/** can be used in Link ** /} <Link {...dashboardLinkOptions} /> </div> ) } export const Route = createFileRoute('/dashboard')({ component: DashboardComponent, validateSearch: (input) => ({ search: input.search }), beforeLoad: () => { // can used in redirect throw redirect(dashboardLinkOptions) }, }) ``` -------------------------------- ### Create Typed Root Route (Solid) Source: https://tanstack.com/router/latest/docs/guide/router-context.md Use `createRootRouteWithContext` to define a typed root router context for your Solid application. This ensures type safety for injected dependencies. ```tsx import { createRootRouteWithContext, createRouter, } from '@tanstack/solid-router' interface MyRouterContext { user: User } // Use the routerContext to create your root route const rootRoute = createRootRouteWithContext<MyRouterContext>()({ component: App, }) const routeTree = rootRoute.addChildren([ // ... ]) // Use the routerContext to create your router const router = createRouter({ routeTree, }) ``` -------------------------------- ### Accessing Route APIs with getRouteApi in Solid Source: https://tanstack.com/router/latest/docs/guide/code-splitting.md Demonstrates using the getRouteApi helper function in SolidJS to access type-safe route APIs such as useLoaderData, useParams, etc., within a component file without needing to import the route directly. ```tsx import { createRoute } from '@tanstack/solid-router' import { MyComponent } from './MyComponent' const route = createRoute({ path: '/my-route', loader: () => ({ foo: 'bar', }), component: MyComponent, }) ``` ```tsx import { getRouteApi } from '@tanstack/solid-router' const route = getRouteApi('/my-route') export function MyComponent() { const loaderData = route.useLoaderData() // ^? { foo: string } return <div>...</div> } ``` -------------------------------- ### Imperative Navigation with Optional Parameters Source: https://tanstack.com/router/latest/docs/guide/navigation.md Use the useNavigate hook to perform navigation with optional parameters. Parameters can be cleared or updated using object or function patterns. ```tsx function Component() { const navigate = useNavigate() const clearFilters = () => { navigate({ to: '/posts/{-$category}/{-$tag}', params: { category: undefined, tag: undefined }, }) } const setCategory = (category: string) => { navigate({ to: '/posts/{-$category}/{-$tag}', params: (prev) => ({ ...prev, category }), }) } const applyFilters = (category?: string, tag?: string) => { navigate({ to: '/posts/{-$category}/{-$tag}', params: { category, tag }, }) } } ``` -------------------------------- ### Create Hash History for React and Solid Routers Source: https://tanstack.com/router/latest/docs/guide/history-types.md Illustrates the creation of a hash history instance for TanStack Router. This method is beneficial in environments where server rewrites to index.html are not feasible, using the URL hash for history management. ```typescript import { createHashHistory, createRouter } from '@tanstack/react-router' const hashHistory = createHashHistory() const router = createRouter({ routeTree, history: hashHistory }) ``` ```typescript import { createHashHistory, createRouter } from '@tanstack/solid-router' const hashHistory = createHashHistory() const router = createRouter({ routeTree, history: hashHistory }) ``` -------------------------------- ### Define a route loader with TanStack Query Source: https://tanstack.com/router/latest/docs/integrations/query.md Uses queryOptions to define a query and triggers it within the route loader to enable streaming to the client. ```tsx import { createFileRoute } from '@tanstack/react-router' import { queryOptions, useQuery } from '@tanstack/react-query' const userQuery = (id: string) => queryOptions({ queryKey: ['user', id], queryFn: () => fetch(`/api/users/${id}`).then((r) => r.json()), }) export const Route = createFileRoute('/user/$id')({ loader: ({ params }) => { // do not await this nor return the promise, just kick off the query to stream it to the client context.queryClient.fetchQuery(userQuery(params.id)) }, }) ``` -------------------------------- ### Update Main Entry File with Router Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-location.md Configures and renders the TanStack Router in the main application entry point (`src/index.tsx`). This involves creating a router instance with the generated route tree and wrapping the application with `RouterProvider`. ```tsx // src/index.tsx import React from 'react' import ReactDOM from 'react-dom' import { createRouter, RouterProvider } from '@tanstack/react-router' // Import the generated route tree import { routeTree } from './routeTree.gen' // Create a new router instance const router = createRouter({ routeTree }) // Register the router instance for type safety declare module '@tanstack/react-router' { interface Register { router: typeof router } } const domElementId = 'root' // Assuming you have a root element with the id 'root' // Render the app const rootElement = document.getElementById(domElementId) if (!rootElement) { throw new Error(`Element with id ${domElementId} not found`) } ReactDOM.createRoot(rootElement).render( <React.StrictMode> <RouterProvider router={router} /> </React.StrictMode>, ) ``` -------------------------------- ### Wrap Router with Context Provider Source: https://tanstack.com/router/latest/docs/api/router/RouterOptionsType.md Demonstrates how to use the Wrap property to provide a React context to the entire router instance. This should only be used for non-DOM rendering components like providers. ```tsx import { createRouter } from '@tanstack/react-router' const router = createRouter({ // ... Wrap: ({ children }) => { return <MyContext.Provider value={myContext}>{children}</MyContext> }, }) ``` -------------------------------- ### Resetting Mutation State with Mutation Keys Source: https://tanstack.com/router/latest/docs/guide/data-mutations.md Demonstrates how to bind a mutation's state to a route parameter using a key. When the roomId changes, the mutation state is automatically cleared. ```tsx const routeApi = getRouteApi('/room/$roomId/chat') function ChatRoom() { const { roomId } = routeApi.useParams() const sendMessageMutation = useCoolMutation({ fn: sendMessage, key: ['sendMessage', roomId], }) const test = () => { sendMessageMutation.mutate({ roomId, message: 'Hello!' }) sendMessageMutation.mutate({ roomId, message: 'How are you?' }) sendMessageMutation.mutate({ roomId, message: 'Goodbye!' }) } return ( <> {sendMessageMutation.submissions.map((submission) => { return ( <div> <div>{submission.status}</div> <div>{submission.message}</div> </div> ) })} </> ) } ``` -------------------------------- ### Default Configuration for React Projects Source: https://tanstack.com/router/latest/docs/installation/with-router-cli.md Default configuration options for TanStack Router CLI when targeting React projects. ```json { "routesDirectory": "./src/routes", "generatedRouteTree": "./src/routeTree.gen.ts", "routeFileIgnorePrefix": "-", "quoteStyle": "single", "target": "react" } ``` -------------------------------- ### Navigate with Fully Optional Parameters Source: https://tanstack.com/router/latest/docs/guide/navigation.md Define routes where all path segments are optional. Set parameters to undefined to remove them from the URL. ```tsx // Navigate to specific date <Link to="/{-$year}/{-$month}/{-$day}" params={{ year: '2023', month: '12', day: '25' }} > Christmas 2023 </Link> // Navigate to partial date <Link to="/{-$year}/{-$month}/{-$day}" params={{ year: '2023', month: '12', day: undefined }} > December 2023 </Link> // Navigate to root with all parameters removed <Link to="/{-$year}/{-$month}/{-$day}" params={{ year: undefined, month: undefined, day: undefined }} > Home </Link> ``` -------------------------------- ### Accessing the Root Route's Match Source: https://tanstack.com/router/latest/docs/api/router/useMatchHook.md Demonstrates how to use `useMatch` with the `rootRouteId` token to access the root route's match information. ```APIDOC ## Example: Accessing the root route's match ### Description This example shows how to use `useMatch` with the `rootRouteId` token to specifically access the match object for the root route. ### Code ```tsx import { useMatch, rootRouteId, // Use this token } from '@tanstack/react-router' function Component() { const match = useMatch({ from: rootRouteId }) // match is a strict RouteMatch object for the root route // ... } ``` ``` -------------------------------- ### Implement Code Splitting with .lazy.tsx Source: https://tanstack.com/router/latest/docs/guide/code-splitting.md Demonstrates splitting a route file into a critical configuration file and a lazy-loaded component file. This approach separates the loader logic from the UI component to improve initial load performance. ```tsx import { createFileRoute } from '@tanstack/react-router'; import { fetchPosts } from './api'; export const Route = createFileRoute('/posts')({ loader: fetchPosts, }); ``` ```tsx import { createLazyFileRoute } from '@tanstack/react-router'; export const Route = createLazyFileRoute('/posts')({ component: Posts, }); function Posts() { // ... } ``` -------------------------------- ### Importing TanStack Router Devtools Source: https://tanstack.com/router/latest/docs/devtools.md Import the standard devtools component for development environments. Use the 'InProd' variant if you need to force the devtools to appear in production builds. ```tsx import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'; import { TanStackRouterDevtoolsInProd } from '@tanstack/react-router-devtools'; ``` ```tsx import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools'; import { TanStackRouterDevtoolsInProd } from '@tanstack/solid-router-devtools'; ``` -------------------------------- ### Implement Code-Splitting in Routes Source: https://tanstack.com/router/latest/docs/decisions-on-dx.md Illustrates how to use lazyRouteComponent to dynamically import route components, reducing initial bundle size in manual route configurations. ```typescript import { createRoute, lazyRouteComponent } from '@tanstack/react-router' import { postsRoute } from './postsRoute' export const postsIndexRoute = createRoute({ getParentRoute: () => postsRoute, path: '/', component: lazyRouteComponent(() => import('../page-components/posts/index')), }) ``` -------------------------------- ### Route Head Configuration Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md Configure head tags for a route using the `head` property in `createRootRoute`. ```APIDOC ## Route Head Configuration ### Description Configure head tags for a route using the `head` property in `createRootRoute`. ### Method N/A (Configuration) ### Endpoint N/A (Configuration) ### Parameters #### Request Body - **head** (function) - Required - A function that returns an object with `title`, `meta`, `links`, `styles`, and `scripts` properties. - **meta** (array) - Optional - An array of meta tag objects. - **name** (string) - Optional - The name attribute for the meta tag. - **content** (string) - Optional - The content attribute for the meta tag. - **title** (string) - Optional - The title for the document. - **links** (array) - Optional - An array of link tag objects. - **rel** (string) - Required - The rel attribute for the link tag. - **href** (string) - Required - The href attribute for the link tag. - **styles** (array) - Optional - An array of style tag objects. - **media** (string) - Optional - The media attribute for the style tag. - **children** (string) - Required - The content of the style tag. - **scripts** (array) - Optional - An array of script tag objects. - **src** (string) - Optional - The src attribute for the script tag. ### Request Example ```tsx export const Route = createRootRoute({ head: () => ({ meta: [ { name: 'description', content: 'My App is a web application', }, { title: 'My App', }, ], links: [ { rel: 'icon', href: '/favicon.ico', }, ], styles: [ { media: 'all and (max-width: 500px)', children: `p { color: blue; background-color: yellow; }`, }, ], scripts: [ { src: 'https://www.google-analytics.com/analytics.js', }, ], }), }) ``` ### Response N/A (Configuration) ``` -------------------------------- ### Create static links Source: https://tanstack.com/router/latest/docs/guide/navigation.md Basic usage of the Link component for static navigation in React and Solid. ```tsx import { Link } from '@tanstack/react-router' const link = <Link to="/about">About</Link> ``` ```tsx import { Link } from '@tanstack/solid-router' const link = <Link to="/about">About</Link> ``` -------------------------------- ### Implement AuthProvider with Persistence Source: https://tanstack.com/router/latest/docs/how-to/setup-authentication.md Use `useState` and `useEffect` within `AuthProvider` to manage authentication state and restore it from `localStorage` on app load. Includes loading state management. ```tsx export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState<User | null>(null) const [isAuthenticated, setIsAuthenticated] = useState(false) const [isLoading, setIsLoading] = useState(true) // Restore auth state on app load useEffect(() => { const token = localStorage.getItem('auth-token') if (token) { // Validate token with your API fetch('/api/validate-token', { headers: { Authorization: `Bearer ${token}` }, }) .then((response) => response.json()) .then((userData) => { if (userData.valid) { setUser(userData.user) setIsAuthenticated(true) } else { localStorage.removeItem('auth-token') } }) .catch(() => { localStorage.removeItem('auth-token') }) .finally(() => { setIsLoading(false) }) } else { setIsLoading(false) } }, []) // Show loading state while checking auth if (isLoading) { return ( <div className="flex items-center justify-center min-h-screen"> Loading... </div> ) } // ... rest of the provider logic } ``` -------------------------------- ### scripts Method Source: https://tanstack.com/router/latest/docs/api/router/RouteOptionsType.md Shorthand helper for injecting script elements. ```APIDOC ## scripts ### Description A shorthand helper to return only <script> elements, equivalent to the scripts field in the head method. ### Parameters - **ctx** (Object) - Required - Contains matches, match, params, and loaderData. ``` -------------------------------- ### Configure indexToken with Regex Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md Demonstrates how to define a custom regex pattern for identifying index routes in TanStack Router. This allows files like 'home-page.tsx' to be treated as index routes. ```json { "indexToken": { "regex": "[a-z]+-page" } } ``` ```typescript { indexToken: /[a-z]+-page/ } ``` -------------------------------- ### LinkOptions Interface Source: https://tanstack.com/router/latest/docs/guide/navigation.md Interface for configuring link components, extending NavigateOptions. ```APIDOC ## LinkOptions Interface ### Description LinkOptions extends NavigateOptions and provides additional configuration for anchor tag behavior, active state matching, and preloading. ### Properties - **target** (string) - Optional - The standard anchor tag target attribute. - **activeOptions** (object) - Optional - Configuration for active state matching (exact, includeHash, includeSearch, explicitUndefined). - **preload** (false | 'intent') - Optional - If set, preloads the linked route on hover. - **preloadDelay** (number) - Optional - Delay intent preloading by this many milliseconds. - **disabled** (boolean) - Optional - If true, renders the link without the href attribute. ``` -------------------------------- ### Define Post Route with Path Param (Solid) Source: https://tanstack.com/router/latest/docs/guide/path-params.md Defines a route for individual posts using a '$postId' path parameter in Solid. The loader function fetches post data using the extracted `postId`. ```tsx import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params }) => { return fetchPost(params.postId) }, }) ``` -------------------------------- ### Define Route Tree Source: https://tanstack.com/router/latest/docs/guide/creating-a-router.md Demonstrates how to import or define a route tree for the router. This is required for the router to match paths to components. ```tsx import { routeTree } from './routeTree.gen' ``` ```tsx const routeTree = rootRoute.addChildren([ // ... ]) ``` -------------------------------- ### Standalone redirect function Source: https://tanstack.com/router/latest/docs/api/router/redirectFunction.md Demonstrates how to use the standalone `redirect` function to trigger internal redirects using `to` or external redirects using `href`. It also shows how to force the function to throw the redirect object. ```APIDOC ## Standalone redirect function ### Description Returns a new `Redirect` object that can be returned or thrown from route callbacks like `beforeLoad` or `loader` to trigger a redirect. ### Method `redirect(options: RedirectOptions)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (RedirectOptions) - Required - Options to determine the redirect behavior. - **to** (string) - Optional - The internal route path to redirect to. - **href** (string) - Optional - The external URL to redirect to. - **throw** (boolean) - Optional - If true, the `Redirect` object will be thrown. Defaults to false. ### Request Example ```tsx import { redirect } from '@tanstack/react-router' // Internal redirect throw redirect({ to: '/login', }) // External redirect throw redirect({ href: 'https://authprovider.com/login', }) // Force throw redirect({ to: '/login', throw: true, }) ``` ### Response #### Success Response (200) N/A (This function triggers a redirect, not a typical response) #### Response Example N/A ``` -------------------------------- ### Accessing Route Parameters with useParams Source: https://tanstack.com/router/latest/docs/api/router/useParamsHook.md Demonstrates various ways to use the useParams hook, including direct access, route-specific API usage, parameter selection, and loose typing configurations. ```tsx import { useParams } from '@tanstack/react-router' const routeApi = getRouteApi('/posts/$postId') function Component() { // Access params for a specific route const params = useParams({ from: '/posts/$postId' }) // Access params via the route API const routeParams = routeApi.useParams() // Access a specific parameter using select const postId = useParams({ from: '/posts/$postId', select: (params) => params.postId, }) // Access params with strict mode disabled const looseParams = useParams({ strict: false }) } ``` -------------------------------- ### Inject Data Fetching into Router Context Source: https://tanstack.com/router/latest/docs/guide/router-context.md Demonstrates injecting a data fetching function directly into the router configuration. ```tsx const fetchTodosByUserId = async ({ userId }) => { const response = await fetch(`/api/todos?userId=${userId}`) const data = await response.json() return data } const router = createRouter({ routeTree: rootRoute, context: { userId: '123', fetchTodosByUserId, }, }) ``` -------------------------------- ### Route matching process for /not-a-route Source: https://tanstack.com/router/latest/docs/routing/route-matching.md Visual representation of the matching process for an undefined URL, falling back to the wildcard route. ```text Root ❌ / ❌ about/us ❌ about ❌ blog - / - new - $postId ✅ * ``` -------------------------------- ### Implement i18n with Optional Path Parameters Source: https://tanstack.com/router/latest/docs/guide/path-params.md Use optional locale prefixes to support multi-language routing patterns. ```tsx // Route: /{-$locale}/about export const Route = createFileRoute('/{-$locale}/about')({ component: AboutComponent, }) function AboutComponent() { const { locale } = Route.useParams() const currentLocale = locale || 'en' // Default to English const content = { en: { title: 'About Us', description: 'Learn more about our company.' }, fr: { title: 'À Propos', description: 'En savoir plus sur notre entreprise.', }, es: { title: 'Acerca de', description: 'Conoce más sobre nuestra empresa.', }, } return ( <div> <h1>{content[currentLocale]?.title}</h1> <p>{content[currentLocale]?.description}</p> </div> ) } ``` -------------------------------- ### TanStack Router Configuration File Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-location.md Create a tsr.config.json file in your project root to specify the directory for routes and the output file for the generated route tree. ```json { "routesDirectory": "./src/routes", "generatedRouteTree": "./src/routeTree.gen.ts" } ``` -------------------------------- ### Create Authentication Context (src/auth.tsx) Source: https://tanstack.com/router/latest/docs/how-to/setup-authentication.md Sets up a React Context for authentication state, including user information, authentication status, and login/logout functions. It also includes logic to restore authentication state from localStorage on app load. ```tsx import React, { createContext, useContext, useState, useEffect } from 'react' interface User { id: string username: string email: string } interface AuthState { isAuthenticated: boolean user: User | null login: (username: string, password: string) => Promise<void> logout: () => void } const AuthContext = createContext<AuthState | undefined>(undefined) export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState<User | null>(null) const [isAuthenticated, setIsAuthenticated] = useState(false) const [isLoading, setIsLoading] = useState(true) // Restore auth state on app load useEffect(() => { const token = localStorage.getItem('auth-token') if (token) { // Validate token with your API fetch('/api/validate-token', { headers: { Authorization: `Bearer ${token}` }, }) .then((response) => response.json()) .then((userData) => { if (userData.valid) { setUser(userData.user) setIsAuthenticated(true) } else { localStorage.removeItem('auth-token') } }) .catch(() => { localStorage.removeItem('auth-token') }) .finally(() => { setIsLoading(false) }) } else { setIsLoading(false) } }, []) // Show loading state while checking auth if (isLoading) { return ( <div className="flex items-center justify-center min-h-screen"> Loading... </div> ) } const login = async (username: string, password: string) => { // Replace with your authentication logic const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }), }) if (response.ok) { const userData = await response.json() setUser(userData) setIsAuthenticated(true) // Store token for persistence localStorage.setItem('auth-token', userData.token) } else { throw new Error('Authentication failed') } } const logout = () => { setUser(null) setIsAuthenticated(false) localStorage.removeItem('auth-token') } return ( <AuthContext.Provider value={{ isAuthenticated, user, login, logout }}> {children} </AuthContext.Provider> ) } export function useAuth() { const context = useContext(AuthContext) if (context === undefined) { throw new Error('useAuth must be used within an AuthProvider') } return context } ``` -------------------------------- ### Implement Basic i18n Route in Solid Source: https://tanstack.com/router/latest/docs/guide/path-params.md Uses an optional locale parameter to render localized content in a Solid component. ```tsx // Route: /{-$locale}/about export const Route = createFileRoute('/{-$locale}/about')({ component: AboutComponent, }) function AboutComponent() { const params = Route.useParams() const currentLocale = params().locale || 'en' // Default to English const content = { en: { title: 'About Us', description: 'Learn more about our company.' }, fr: { title: 'À Propos', description: 'En savoir plus sur notre entreprise.', }, es: { title: 'Acerca de', description: 'Conoce más sobre nuestra empresa.', }, } return ( <div> <h1>{content[currentLocale]?.title}</h1> <p>{content[currentLocale]?.description}</p> </div> ) } ``` -------------------------------- ### Create Protected Route with Authentication Guard Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Sets up a base route for authenticated users. It uses `beforeLoad` to check authentication status and redirects to sign-in if not authenticated. ```tsx import { createFileRoute, redirect, Outlet } from '@tanstack/react-router' export const Route = createFileRoute('/_authenticated')({ beforeLoad: ({ context, location }) => { if (!context.auth.isAuthenticated) { throw redirect({ to: '/sign-in', search: { redirect: location.href, }, }) } }, component: () => <Outlet />, }) ``` -------------------------------- ### Configure Router (src/router.tsx) Source: https://tanstack.com/router/latest/docs/how-to/setup-authentication.md Creates the TanStack Router instance, specifying the route tree and the initial context. The 'auth' context is declared as undefined initially and will be provided by the App component. ```tsx import { createRouter } from '@tanstack/react-router' import { routeTree } from './routeTree.gen' export const router = createRouter({ routeTree, context: { // auth will be passed down from App component auth: undefined!, }, }) declare module '@tanstack/react-router' { interface Register { router: typeof router } } ``` -------------------------------- ### Clerk Environment Variables Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Configure your Clerk publishable key in your .env file. This key is necessary for Clerk to function. ```env VITE_CLERK_PUBLISHABLE_KEY=pk_test_your_clerk_key ``` -------------------------------- ### Block navigation based on route patterns Source: https://tanstack.com/router/latest/docs/guide/navigation-blocking.md Demonstrates how to use the shouldBlockFn callback to target specific route transitions using current and next location objects. ```tsx import { useBlocker } from '@tanstack/react-router' function MyComponent() { const { proceed, reset, status } = useBlocker({ shouldBlockFn: ({ current, next }) => { return ( current.routeId === '/foo' && next.fullPath === '/bar/$id' && next.params.id === 123 && next.search.hello === 'world' ) }, withResolver: true, }) } ``` ```tsx import { useBlocker } from '@tanstack/solid-router' function MyComponent() { const { proceed, reset, status } = useBlocker({ shouldBlockFn: ({ current, next }) => { return ( current.routeId === '/foo' && next.fullPath === '/bar/$id' && next.params.id === 123 && next.search.hello === 'world' ) }, withResolver: true, }) } ``` -------------------------------- ### RouteOptions Configuration Source: https://tanstack.com/router/latest/docs/api/router/RouteOptionsType.md Defines the properties and methods required to configure a route within the TanStack Router framework. ```APIDOC ## RouteOptions Configuration ### Description The RouteOptions object is used to define the configuration for a specific route, including its hierarchy, path matching, and rendering behavior. ### Parameters #### Properties - **getParentRoute** (function) - Required - Returns the parent route for type safety. - **path** (string) - Required (unless id is provided) - The path segment for matching. - **id** (string) - Optional - Unique identifier for pathless layout routes. - **component** (RouteComponent) - Optional - Content to render when matched. - **errorComponent** (RouteComponent) - Optional - Content to render on error. - **pendingComponent** (RouteComponent) - Optional - Content to render while pending. - **notFoundComponent** (NotFoundRouteComponent) - Optional - Content to render when not found. - **validateSearch** (function) - Optional - Validates and parses search parameters. - **search.middlewares** (array) - Optional - Transforms search parameters for links. - **params.parse** (function) - Optional - Parses raw URL parameters. - **params.stringify** (function) - Optional - Stringifies parameters for URL generation. ### Request Example { "path": "/users/:userId", "component": UserComponent, "validateSearch": (search) => ({ page: Number(search.page) || 1 }) } ### Response #### Success Response (200) - **Route** (object) - Returns a configured route object ready for the router tree. ``` -------------------------------- ### Configuring Structural Sharing Source: https://tanstack.com/router/latest/docs/guide/render-optimizations.md Shows how to enable structural sharing globally in the router configuration or locally within a specific hook to maintain referential stability for objects returned by selectors. ```tsx const router = createRouter({ routeTree, defaultStructuralSharing: true, }) ``` ```tsx const result = Route.useSearch({ select: (search) => ({ foo: search.foo, hello: `hello ${search.foo}`, }), structuralSharing: true, }) ``` -------------------------------- ### React: Query-String Library for Search Param Serialization Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md Demonstrates using the 'query-string' library with TanStack Router in React for parsing and stringifying search parameters. This provides reliable handling of query string formats. ```tsx import { createRouter } from '@tanstack/react-router' import qs from 'query-string' const router = createRouter({ // ... stringifySearch: stringifySearchWith((value) => qs.stringify(value, { // ...options }), ), parseSearch: parseSearchWith((value) => qs.parse(value, { // ...options }), ), }) ``` -------------------------------- ### LinkOptions Interface Source: https://tanstack.com/router/latest/docs/guide/navigation.md Extends NavigateOptions to provide configuration for anchor tag rendering, active state matching, and preloading behavior. ```tsx export type LinkOptions< TRouteTree extends AnyRoute = AnyRoute, TFrom extends RoutePaths<TRouteTree> | string = string, TTo extends string = '', > = NavigateOptions<TRouteTree, TFrom, TTo> & { // The standard anchor tag target attribute target?: HTMLAnchorElement['target'] // Defaults to `{ exact: false, includeHash: false }` activeOptions?: { exact?: boolean includeHash?: boolean includeSearch?: boolean explicitUndefined?: boolean } // If set, will preload the linked route on hover and cache it for this many milliseconds in hopes that the user will eventually navigate there. preload?: false | 'intent' // Delay intent preloading by this many milliseconds. If the intent exits before this delay, the preload will be cancelled. preloadDelay?: number // If true, will render the link without the href attribute disabled?: boolean } ``` -------------------------------- ### Importing Router Instance for Type Inference Source: https://tanstack.com/router/latest/docs/decisions-on-dx.md Shows how to import the Router instance directly into components to leverage its type information for props like the 'to' and 'params' in the Link component. This method can increase bundle size and management overhead. ```tsx import { router } from '@/src/app' export const PostsIdLink = () => { return ( <Link<typeof router> to="/posts/$postId" params={{ postId: '123' }}> Go to post 123 </Link> ) } ``` -------------------------------- ### Pass Initial Router Context (React) Source: https://tanstack.com/router/latest/docs/guide/router-context.md Instantiate the router with an initial context object. This context will be available to all routes and can be used for dependency injection. ```tsx import { createRouter } from '@tanstack/react-router' // Use the routerContext you created to create your router const router = createRouter({ routeTree, context: { user: { id: '123', name: 'John Doe', }, }, }) ``` -------------------------------- ### Solid: JSURL2 Library for Compressed Search Param Serialization Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md Utilizes the JSURL2 library with TanStack Router in SolidJS for search parameter serialization. This approach compresses URLs, offering a balance between size and readability. ```tsx import { Router, parseSearchWith, stringifySearchWith, } from '@tanstack/solid-router' import { parse, stringify } from 'jsurl2' const router = createRouter({ // ... parseSearch: parseSearchWith(parse), stringifySearch: stringifySearchWith(stringify), }) ``` -------------------------------- ### Mount Physical Directory under a Path Source: https://tanstack.com/router/latest/docs/routing/virtual-file-routes.md Use the `physical` function to mount a directory of standard file-based routes under a specific URL path. This requires importing `physical`, `rootRoute`, and `route`. ```typescript // routes.ts export const routes = rootRoute('root.tsx', [ // Set up your virtual routes as normal index('index.tsx'), layout('pathlessLayout.tsx', [ route('/dashboard', 'app/dashboard.tsx', [ index('app/dashboard-index.tsx'), route('/invoices', 'app/dashboard-invoices.tsx', [ index('app/invoices-index.tsx'), route('$id', 'app/invoice-detail.tsx'), ]), ]), // Mount the `posts` directory under the `/posts` path physical('/posts', 'posts'), ]), ]) ``` -------------------------------- ### Injecting Route-Specific Context with `beforeLoad` in Solid Source: https://tanstack.com/router/latest/docs/guide/data-loading.md Use the `beforeLoad` option to inject data into a route's context before the loader runs. This function receives the same parameters as `loader` and can return an object to merge into the context. ```tsx // src/routes/posts.tsx export const Route = createFileRoute('/posts')({ // Pass the fetchPosts function to the route context beforeLoad: () => ({ fetchPosts: () => console.info('foo'), }), loader: ({ context: { fetchPosts } }) => { fetchPosts() // 'foo' // ... }, }) ``` -------------------------------- ### Create a Basic Route Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md Use `createRoute` to define a route with a specific path. The `getParentRoute` function is required for type safety. ```tsx const route = createRoute({ getParentRoute: () => rootRoute, path: '/posts', component: PostsComponent, }) ``` -------------------------------- ### Implement Navigation Blocking with useBlocker Source: https://tanstack.com/router/latest/docs/api/router/useBlockerHook.md This snippet demonstrates how to use the useBlocker hook to prevent navigation when specific route criteria are met. It checks the current route, target path, parameters, and search query to determine if the transition should be blocked. ```tsx import { useBlocker } from '@tanstack/react-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = useState(false) const { proceed, reset, status } = useBlocker({ shouldBlockFn: ({ current, next }) => { if ( current.routeId === '/editor-1' && next.fullPath === '/foo/$id' && next.params.id === '123' && next.search.hello === 'world' ) { return true } return false }, enableBeforeUnload: false, withResolver: true, }) // ... } ``` -------------------------------- ### TanStack Router: beforeLoad Method Source: https://tanstack.com/router/latest/docs/api/router/RouteOptionsType.md The beforeLoad method is an optional async function executed before a route is loaded. It can be used for authentication checks and redirects. If it returns a promise, the route enters a pending state. If it returns a TRouteContext object, it's merged into the route's context. Errors thrown here can cancel navigation or fail preloads. ```typescript type beforeLoad = ( opts: RouteMatch & { search: TFullSearchSchema abortController: AbortController preload: boolean params: TAllParams context: TParentContext location: ParsedLocation navigate: NavigateFn<AnyRoute> // @deprecated buildLocation: BuildLocationFn<AnyRoute> cause: 'enter' | 'stay' }, ) => Promise<TRouteContext> | TRouteContext | void ``` -------------------------------- ### File-Based Route Tree Configuration Source: https://tanstack.com/router/latest/docs/routing/route-trees.md Shows a typical file-based route tree structure for a TanStack Router application, including root, index, about, posts, settings, and pathless layouts. ```directory /routes ├── __root.tsx ├── index.tsx ├── about.tsx ├── posts/ │ ├── index.tsx │ ├── $postId.tsx ├── posts.$postId.edit.tsx ├── settings/ │ ├── profile.tsx │ ├── notifications.tsx ├── _pathlessLayout/ │ ├── route-a.tsx ├── ├── route-b.tsx ├── files/ │ ├── $.tsx ``` -------------------------------- ### Implement Custom UI with useBlocker Resolver Source: https://tanstack.com/router/latest/docs/guide/navigation-blocking.md Uses the useBlocker hook with withResolver enabled to manually control navigation state via custom UI components. ```tsx import { useBlocker } from '@tanstack/react-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = useState(false) const { proceed, reset, status } = useBlocker({ shouldBlockFn: () => formIsDirty, withResolver: true, }) return ( <> {status === 'blocked' && ( <div> <p>Are you sure you want to leave?</p> <button onClick={proceed}>Yes</button> <button onClick={reset}>No</button> </div> )} </> ) } ``` ```tsx import { useBlocker } from '@tanstack/solid-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = createSignal(false) const { proceed, reset, status } = useBlocker({ shouldBlockFn: () => formIsDirty(), withResolver: true, }) return ( <> {status === 'blocked' && ( <div> <p>Are you sure you want to leave?</p> <button onClick={proceed}>Yes</button> <button onClick={reset}>No</button> </div> )} </> ) } ``` -------------------------------- ### Create a Pathless Layout Route in Solid Source: https://tanstack.com/router/latest/docs/routing/routing-concepts.md Defines a route that acts as a layout wrapper without contributing to the URL path. ```tsx import { Outlet, createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/_pathlessLayout')({ component: PathlessLayoutComponent, }) function PathlessLayoutComponent() { return ( <div> <h1>Pathless layout</h1> <Outlet /> </div> ) } ``` -------------------------------- ### Build the Route Tree Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md Construct the complete route tree by adding child routes to their respective parent routes using the `addChildren` method. ```tsx /* prettier-ignore */ const routeTree = rootRoute.addChildren([ indexRoute, aboutRoute, postsRoute.addChildren([ postsIndexRoute, postRoute, ]), postEditorRoute, settingsRoute.addChildren([ profileRoute, notificationsRoute, ]), pathlessLayoutRoute.addChildren([ pathlessLayoutARoute, pathlessLayoutBRoute, ]), filesRoute.addChildren([ fileRoute, ]), ]) /* prettier-ignore-end */ ``` -------------------------------- ### Using useSuspenseQuery vs useQuery in Components Source: https://tanstack.com/router/latest/docs/integrations/query.md Use `useSuspenseQuery` for data required during SSR, as it executes on the server and streams to the client. `useQuery` does not execute on the server and fetches only on the client after hydration, suitable for non-critical data. ```tsx // Suspense: executes on server and streams const { data } = useSuspenseQuery(postsQuery) // Non-suspense: executes only on client const { data, isLoading } = useQuery(postsQuery) ``` -------------------------------- ### useMatchRoute and <MatchRoute> Source: https://tanstack.com/router/latest/docs/guide/navigation.md Utilities to check if a specific route is currently active or pending. ```APIDOC ## useMatchRoute / <MatchRoute> ### Description Checks if a route is currently matched. The hook returns a function, while the component can render children based on the match state. ### Parameters - **to** (string) - Required - The route path to check. - **pending** (boolean) - Optional - If true, returns true if the route is currently transitioning. ``` -------------------------------- ### Create Memory History for React and Solid Routers Source: https://tanstack.com/router/latest/docs/guide/history-types.md Demonstrates how to create a memory history instance for TanStack Router. This is useful for server-side rendering or testing, allowing history to be managed in memory without interacting with the browser's URL. ```typescript import { createMemoryHistory, createRouter } from '@tanstack/react-router' const memoryHistory = createMemoryHistory({ initialEntries: ['/'], // Pass your initial url }) const router = createRouter({ routeTree, history: memoryHistory }) ``` ```typescript import { createMemoryHistory, createRouter } from '@tanstack/solid-router' const memoryHistory = createMemoryHistory({ initialEntries: ['/'], // Pass your initial url }) const router = createRouter({ routeTree, history: memoryHistory }) ``` -------------------------------- ### Load API Source: https://tanstack.com/router/latest/docs/api/router/RouterType.md Loads all currently matched route matches and resolves when they are ready to be rendered. Useful for Server-Side Rendering (SSR). ```APIDOC ## load Method ### Description Loads all of the currently matched route matches and resolves when they are all loaded and ready to be rendered. ### Method `load` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **opts** (object) - Optional - Options for loading. - **sync** (boolean) - Optional - If `true`, the promise resolves only after all loaders have finished. ### Request Example ```json { "sync": true } ``` ### Response #### Success Response (200) This method returns a Promise that resolves when all route matches are loaded. #### Response Example ```json null ``` ``` -------------------------------- ### TanStackRouterDevtools Configuration Source: https://tanstack.com/router/latest/docs/devtools.md Configuration options for the main TanStack Router Devtools component. ```APIDOC ## TanStackRouterDevtools Options ### Description Configuration properties for the floating TanStack Router Devtools component. ### Parameters - **router** (Router) - Required - The router instance to connect to. - **initialIsOpen** (Boolean) - Optional - Set true to default to open state. - **panelProps** (PropsObject) - Optional - Props to apply to the devtools panel. - **closeButtonProps** (PropsObject) - Optional - Props to apply to the close button. - **toggleButtonProps** (PropsObject) - Optional - Props to apply to the toggle button. - **position** ("top-left" | "top-right" | "bottom-left" | "bottom-right") - Optional - Defaults to 'bottom-left'. - **shadowDOMTarget** (ShadowRoot) - Optional - Specifies a Shadow DOM target for styles. - **containerElement** (string | any) - Optional - Custom container element, defaults to 'footer'. ``` -------------------------------- ### Authentication using React Context/Hooks Source: https://tanstack.com/router/latest/docs/guide/authenticated-routes.md Explains how to integrate authentication state from React context or hooks into TanStack Router using the `router.context` option. ```APIDOC # React <!-- ::start:tabs variant="files" --> ```tsx title="src/routes/__root.tsx" import { createRootRouteWithContext } from '@tanstack/react-router' interface MyRouterContext { // The ReturnType of your useAuth hook or the value of your AuthContext auth: AuthState } export const Route = createRootRouteWithContext<MyRouterContext>()({ component: () => <Outlet />, }) ``` ```tsx title="src/router.tsx" import { createRouter } from '@tanstack/react-router' import { routeTree } from './routeTree.gen' export const router = createRouter({ routeTree, context: { // auth will initially be undefined // We'll be passing down the auth state from within a React component auth: undefined!, }, }) ``` ```tsx title="src/App.tsx" import { RouterProvider } from '@tanstack/react-router' import { AuthProvider, useAuth } from './auth' import { router } from './router' function InnerApp() { const auth = useAuth() return <RouterProvider router={router} context={{ auth }} /> } function App() { return ( <AuthProvider> <InnerApp /> </AuthProvider> ) } ``` <!-- ::end:tabs --> # Solid <!-- ::start:tabs variant="files" --> ```tsx title="src/routes/__root.tsx" import { createRootRouteWithContext } from '@tanstack/solid-router' interface MyRouterContext { // The ReturnType of your useAuth hook or the value of your AuthContext auth: AuthState } export const Route = createRootRouteWithContext<MyRouterContext>()({ component: () => <Outlet />, }) ``` ```tsx title="src/router.tsx" import { createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' export const router = createRouter({ routeTree, context: { // auth will initially be undefined // We'll be passing down the auth state from within a React component auth: undefined!, }, }) ``` ```tsx title="src/App.tsx" import { RouterProvider } from '@tanstack/solid-router' import { AuthProvider, useAuth } from './auth' import { router } from './router' function InnerApp() { const auth = useAuth() return <RouterProvider router={router} context={{ auth }} /> } function App() { return ( <AuthProvider> <InnerApp /> </AuthProvider> ) } ``` <!-- ::end:tabs --> ``` -------------------------------- ### Route File Naming Conventions and Ignoring Files Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md Defines how files are identified as routes and how specific files or directories can be excluded from routing. The `routeFilePrefix` determines which files are considered, while `routeFileIgnorePrefix` and `routeFileIgnorePattern` allow for explicit exclusion of non-route files or directories, such as component co-locations. ```txt src/routes ├── posts │ ├── -components // Ignored │ │ ├── Post.tsx │ ├── index.tsx │ ├── route.tsx ``` -------------------------------- ### head Method Source: https://tanstack.com/router/latest/docs/api/router/RouteOptionsType.md Injects SEO metadata, links, styles, and scripts into the document head. ```APIDOC ## head ### Description Returns additional elements to inject into the document <head> for this route. ### Parameters - **ctx** (Object) - Required - Contains matches, match, params, and loaderData. ### Response - **Returns** (Object) - Contains optional fields: links, scripts, meta, and styles. ``` -------------------------------- ### Combine Optional Path Parameters with Search Parameters Source: https://tanstack.com/router/latest/docs/guide/navigation.md Optional path parameters can be used alongside search parameters. Use a function in the search prop to preserve existing search state. ```tsx // Combine optional path params with search params <Link to="/posts/{-$category}" params={{ category: 'tech' }} search={{ page: 1, sort: 'newest' }} > Tech Posts - Page 1 </Link> // Remove path param but keep search params <Link to="/posts/{-$category}" params={{ category: undefined }} search={(prev) => prev} > All Posts - Same Filters </Link> ``` -------------------------------- ### Create Router Instance Source: https://tanstack.com/router/latest/docs/guide/ssr.md Defines the router factory and registers the router type for the application. ```tsx import { createRouter as createTanstackRouter } from '@tanstack/react-router' import { routeTree } from './routeTree.gen' export function createRouter() { return createTanstackRouter({ routeTree }) } declare module '@tanstack/react-router' { interface Register { router: ReturnType<typeof createRouter> } } ``` ```tsx import { createRouter as createTanstackRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' export function createRouter() { return createTanstackRouter({ routeTree }) } declare module '@tanstack/solid-router' { interface Register { router: ReturnType<typeof createRouter> } } ``` -------------------------------- ### Route.redirect usage in File-Based Routes Source: https://tanstack.com/router/latest/docs/api/router/redirectFunction.md Illustrates using `Route.redirect` within file-based routing with `createFileRoute`. This method simplifies redirects by automatically inferring the 'from' parameter, enabling type-safe relative path usage for internal navigation. ```tsx // In routes/dashboard/settings.tsx import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/dashboard/settings')({ beforeLoad: ({ context }) => { if (!context.user) { // Relative redirect - automatically knows we're redirecting from '/dashboard/settings' throw Route.redirect({ to: '../login', // Redirects to '/dashboard/login' }) } }, loader: () => { // Also works in loader if (needsMigration) { throw Route.redirect({ to: './migrate', // Redirects to '/dashboard/settings/migrate' }) } }, }) ``` -------------------------------- ### Interaction with Basepath Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Demonstrates how custom rewrites interact with the `basepath` configuration. Input rewrites run after the basepath is stripped, and output rewrites run before the basepath is added. ```tsx const router = createRouter({ routeTree, basepath: '/app', rewrite: { input: ({ url }) => { // This runs AFTER basepath is stripped // Browser: /app/en/about → After basepath: /en/about → Your rewrite: /about return url }, output: ({ url }) => { // This runs BEFORE basepath is added // Your rewrite: /about → After your rewrite: /en/about → Basepath adds: /app/en/about return url }, }, }) ``` -------------------------------- ### Create Simple MUI Link Integration Source: https://tanstack.com/router/latest/docs/guide/custom-link.md Wraps a standard MUI Link component with createLink to enable router navigation. This is the simplest way to make an existing UI component compatible with TanStack Router. ```tsx import { createLink } from '@tanstack/react-router' import { Link } from '@mui/material' export const CustomLink = createLink(Link) ``` -------------------------------- ### Define Static Data in Routes Source: https://tanstack.com/router/latest/docs/guide/static-route-data.md Demonstrates how to attach a staticData object to a route definition using createFileRoute. ```tsx import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/posts')({ staticData: { customData: 'Hello!', }, }) ``` ```tsx import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/posts')({ staticData: { customData: 'Hello!', }, }) ``` -------------------------------- ### Index Token Configuration Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md Configure how index routes are identified. By default, it's 'index', but regex patterns can be used for more flexible naming. ```APIDOC ## `indexToken` As mentioned in the Routing Concepts guide, an index route is a route that is matched when the URL path is exactly the same as the parent route. The `indexToken` is used to identify the index route file in the route directory. By default, this value is set to `index`. > 🧠 the following filenames would equal the same runtime URL: ```txt src/routes/posts.index.tsx -> /posts/ src/routes/posts/index.tsx -> /posts/ ``` #### Using regex patterns for `indexToken` Similar to `routeToken`, you can use a regular expression pattern for `indexToken` to match multiple index route naming conventions. **In `tsr.config.json`** (JSON config): ```json { "indexToken": { "regex": "[a-z]+-page" } } ``` **In code** (inline config): ```ts { indexToken: /[a-z]+-page/ } ``` With the regex pattern `[a-z]+-page`, filenames like `home-page.tsx`, `posts.list-page.tsx`, or `dashboard.overview-page.tsx` would all be recognized as index routes. #### Escaping regex tokens When using regex tokens, you can still escape a segment to prevent it from being treated as a token by wrapping it in square brackets. For example, if your `indexToken` is `{ "regex": "[a-z]+-page" }` and you want a literal route segment called `home-page`, name your file `[home-page].tsx`. ``` -------------------------------- ### Utilize Virtual Routes for Clean File Structure Source: https://tanstack.com/router/latest/docs/guide/code-splitting.md Shows how to remove empty route files entirely, allowing TanStack Router to generate a virtual route automatically. This is ideal when a route file contains no logic other than the lazy-loaded component. ```tsx import { createLazyFileRoute } from '@tanstack/react-router'; export const Route = createLazyFileRoute('/posts')({ component: Posts, }); function Posts() { // ... } ``` -------------------------------- ### RouteApi Constructor Source: https://tanstack.com/router/latest/docs/api/router/RouteApiClass.md Initializes a new RouteApi instance bound to a specific route ID to provide type-safe access to route hooks. ```APIDOC ## Constructor: new RouteApi(options) ### Description Creates an instance of RouteApi pre-bound to a specific route ID. This allows for type-safe access to hooks like `useLoaderData`, `useParams`, and `useSearch` for that specific route. ### Parameters #### Options Object - **routeId** (string) - Required - The unique identifier of the route to bind the instance to. ### Usage Example ```tsx import { RouteApi } from '@tanstack/react-router' const routeApi = new RouteApi({ id: '/posts' }) export function PostsPage() { const posts = routeApi.useLoaderData() return <div>{/* ... */}</div> } ``` ### Warning This class is deprecated. Please use the `getRouteApi` function instead for future-proof code. ``` -------------------------------- ### Define React Routes with Code Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md Use `createRootRoute` and `createRoute` to define your application's route tree in code for React. This approach mirrors file-based routing structure but is defined programmatically. ```tsx import { createRootRoute, createRoute } from '@tanstack/react-router' const rootRoute = createRootRoute() const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', }) const aboutRoute = createRoute({ getParentRoute: () => rootRoute, path: 'about', }) const postsRoute = createRoute({ getParentRoute: () => rootRoute, path: 'posts', }) const postsIndexRoute = createRoute({ getParentRoute: () => postsRoute, path: '/', }) const postRoute = createRoute({ getParentRoute: () => postsRoute, path: '$postId', }) const postEditorRoute = createRoute({ getParentRoute: () => rootRoute, path: 'posts/$postId/edit', }) const settingsRoute = createRoute({ getParentRoute: () => rootRoute, path: 'settings', }) const profileRoute = createRoute({ getParentRoute: () => settingsRoute, path: 'profile', }) const notificationsRoute = createRoute({ getParentRoute: () => settingsRoute, path: 'notifications', }) const pathlessLayoutRoute = createRoute({ getParentRoute: () => rootRoute, id: 'pathlessLayout', }) const pathlessLayoutARoute = createRoute({ getParentRoute: () => pathlessLayoutRoute, path: 'route-a', }) const pathlessLayoutBRoute = createRoute({ getParentRoute: () => pathlessLayoutRoute, path: 'route-b', }) const filesRoute = createRoute({ getParentRoute: () => rootRoute, path: 'files/$', }) ``` -------------------------------- ### API Reference: `composeRewrites` function Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Explains the `composeRewrites` function, which combines multiple rewrite configurations into a single one, detailing the execution order of input and output rewrites. ```APIDOC ### `composeRewrites` function ```tsx import { composeRewrites } from '@tanstack/react-router' function composeRewrites(rewrites: Array<LocationRewrite>): LocationRewrite ``` Combines multiple rewrite pairs into a single rewrite. Input rewrites execute in order, output rewrites execute in reverse order. **Example:** ```tsx const composedRewrite = composeRewrites([ { input: rewrite1Input, output: rewrite1Output }, { input: rewrite2Input, output: rewrite2Output }, ]) // Input execution order: rewrite1Input → rewrite2Input // Output execution order: rewrite2Output → rewrite1Output ``` ``` -------------------------------- ### Non-Redirected Authentication Source: https://tanstack.com/router/latest/docs/guide/authenticated-routes.md Demonstrates how to implement authentication without redirecting the user by conditionally rendering the Outlet. ```APIDOC ## Non-Redirected Authentication Some applications choose to not redirect users to a login page, and instead keep the user on the same page and show a login form that either replaces the main content or hides it via a modal. This is also possible with TanStack Router by simply short circuiting rendering the `<Outlet />` that would normally render the child routes: ```tsx // src/routes/_authenticated.tsx export const Route = createFileRoute('/_authenticated')({ component: () => { if (!isAuthenticated()) { return <Login /> } return <Outlet /> }, }) ``` This keeps the user on the same page, but still allows you to render a login form. Once the user is authenticated, you can simply render the `<Outlet />` and the child routes will be rendered. ``` -------------------------------- ### Implement lazyRouteComponent for Route Splitting Source: https://tanstack.com/router/latest/docs/api/router/lazyRouteComponentFunction.md Demonstrates how to use lazyRouteComponent to load route components dynamically. It shows both default import usage and specifying a named export for the component. ```tsx import { lazyRouteComponent } from '@tanstack/react-router' const route = createRoute({ path: '/posts/$postId', component: lazyRouteComponent(() => import('./Post')), }) const routeNamed = createRoute({ path: '/posts/$postId', component: lazyRouteComponent( () => import('./Post'), 'PostByIdPageComponent', ), }) ``` -------------------------------- ### Generate Routes with CLI Source: https://tanstack.com/router/latest/docs/installation/with-router-cli.md Use the 'tsr generate' command to create the route tree for your project based on the provided configuration. ```bash tsr generate ``` -------------------------------- ### Define Routes with All Optional Parameters Source: https://tanstack.com/router/latest/docs/guide/path-params.md Multiple consecutive optional parameters allow for hierarchical optional routing. ```tsx // Route: /{-$year}/{-$month}/{-$day} // Matches: /, /2023, /2023/12, /2023/12/25 export const Route = createFileRoute('/{-$year}/{-$month}/{-$day}')({ component: DateComponent, }) function DateComponent() { const { year, month, day } = Route.useParams() if (!year) return <div>Select a year</div> if (!month) return <div>Year: {year}</div> if (!day) return ( <div> Month: {year}/{month} </div> ) return ( <div> Date: {year}/{month}/{day} </div> ) } ``` ```tsx // Route: /{-$year}/{-$month}/{-$day} // Matches: /, /2023, /2023/12, /2023/12/25 export const Route = createFileRoute('/{-$year}/{-$month}/{-$day}')({ component: DateComponent, }) function DateComponent() { const params = Route.useParams() if (!params().year) return <div>Select a year</div> if (!params().month) return <div>Year: {params().year}</div> if (!params().day) return ( <div> Month: {params().year}/{params().month} </div> ) return ( <div> Date: {params().year}/{params().month}/{params().day} </div> ) } ``` -------------------------------- ### Configure Vite for Solid with TanStack Router Source: https://tanstack.com/router/latest/docs/installation/with-vite.md Integrate the tanstackRouter plugin into your Vite configuration for Solid projects. The plugin should be added before the Solid plugin. ```typescript import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ tanstackRouter({ target: 'solid', autoCodeSplitting: true, }), solid(), // ... ], }) ``` -------------------------------- ### createRootRoute Function Source: https://tanstack.com/router/latest/docs/api/router/createRootRouteFunction.md Initializes a root route instance which acts as the parent for the entire application route tree. ```APIDOC ## createRootRoute ### Description The `createRootRoute` function returns a new root route instance. A root route instance is required to build a route-tree for your application. ### Method N/A (Function Call) ### Parameters #### Options - **options** (RouteOptions) - Optional - Configuration object excluding path, id, getParentRoute, caseSensitive, parseParams, and stringifyParams. ### Request Example ```tsx import { createRootRoute, Outlet } from '@tanstack/react-router' const rootRoute = createRootRoute({ component: () => <Outlet />, }) ``` ### Response #### Success Response - **Route** (Instance) - A new Route instance used to construct the route tree. ``` -------------------------------- ### Style Custom Router Links Source: https://tanstack.com/router/latest/docs/guide/custom-link.md Demonstrates how to apply MUI styled-components to a custom router link component. ```tsx import { css, styled } from '@mui/material' import { CustomLink } from './CustomLink' const StyledCustomLink = styled(CustomLink)( ({ theme }) => css` color: ${theme.palette.common.white}; `, ) ``` -------------------------------- ### Implement Conditional Route Access with beforeLoad Source: https://tanstack.com/router/latest/docs/faq.md Demonstrates how to use the beforeLoad hook to perform authentication checks and redirect unauthorized users. This pattern is applicable to both React and Solid frameworks within TanStack Router. ```tsx // src/routes/_pathless-layout.tsx import { createFileRoute, Outlet } from '@tanstack/react-router' import { isAuthenticated } from '../utils/auth' export const Route = createFileRoute('/_pathless-layout', { beforeLoad: async () => { // Check if the user is authenticated const authed = await isAuthenticated() if (!authed) { // Redirect the user to the login page return '/login' } }, component: PathlessLayoutRouteComponent, // ... }) function PathlessLayoutRouteComponent() { return ( <div> <h1>You are authed</h1> <Outlet /> </div> ) } ``` ```tsx // src/routes/_pathless-layout.tsx import { createFileRoute, Outlet } from '@tanstack/solid-router' import { isAuthenticated } from '../utils/auth' export const Route = createFileRoute('/_pathless-layout', { beforeLoad: async () => { // Check if the user is authenticated const authed = await isAuthenticated() if (!authed) { // Redirect the user to the login page return '/login' } }, component: PathlessLayoutRouteComponent, // ... }) function PathlessLayoutRouteComponent() { return ( <div> <h1>You are authed</h1> <Outlet /> </div> ) } ``` -------------------------------- ### Complex i18n Routing with Optional Parameters Source: https://tanstack.com/router/latest/docs/guide/internationalization-i18n.md Illustrates a more complex routing pattern using multiple optional path parameters for locale, category, and slug. It includes a `beforeLoad` hook to validate the locale against a list of supported locales. ```tsx export const Route = createFileRoute('/{-$locale}/blog/{-$category}/$slug')({ beforeLoad: ({ params }) => { const locale = params.locale || 'en' const validLocales = ['en', 'fr', 'es', 'de'] if (params.locale && !validLocales.includes(params.locale)) { throw new Error('Invalid locale') } return { locale } }, }) ``` -------------------------------- ### Define a basic route Source: https://tanstack.com/router/latest/docs/routing/routing-concepts.md Basic routes match a specific path exactly and render the associated component. ```tsx import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/about')({ component: AboutComponent, }) function AboutComponent() { return <div>About</div> } ``` ```tsx import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/about')({ component: AboutComponent, }) function AboutComponent() { return <div>About</div> } ``` -------------------------------- ### useNavigate Hook for Type-Safe Navigation Source: https://tanstack.com/router/latest/docs/api/router/RouteApiType.md Offers a type-safe wrapper around the `useNavigate` hook, pre-bound to a specific route ID. This simplifies navigation logic by ensuring type safety and context awareness. ```typescript useNavigate(): // navigate function ``` -------------------------------- ### Hard Links for Cross-Origin Rewrites Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Explains how the `<Link>` component renders a standard anchor tag for hard navigation when an output rewrite changes the origin (hostname). ```APIDOC ## Hard Links for Cross-Origin Rewrites When an output rewrite changes the origin (hostname), the `<Link>` component automatically renders a standard anchor tag instead of using client-side navigation: ### Request Example ```tsx // Rewrite that changes hostname for /admin paths const router = createRouter({ routeTree, rewrite: { output: ({ url }) => { if (url.pathname.startsWith('/admin')) { url.hostname = 'admin.example.com' url.pathname = url.pathname.replace(/^\/admin/, '') || '/' } return url }, }, }) // This link will be a hard navigation (full page load) <Link to="/admin/dashboard">Admin Dashboard</Link> // Renders: <a href="https://admin.example.com/dashboard">Admin Dashboard</a> ``` ``` -------------------------------- ### Configuring Custom Search Serialization Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md How to configure the Router instance to use custom serialization logic for URL search parameters. ```APIDOC ## Router Configuration: Search Serialization ### Description Configures the TanStack Router instance to use custom logic for parsing and stringifying URL search parameters instead of the default JSON methods. ### Method Configuration Object (RouterOptions) ### Parameters #### Request Body - **parseSearch** (function) - Optional - A function that takes a string and returns a search object. - **stringifySearch** (function) - Optional - A function that takes a search object and returns a string. ### Request Example ```javascript const router = createRouter({ parseSearch: parseSearchWith(customParser), stringifySearch: stringifySearchWith(customStringifier), }) ``` ### Response #### Success Response (200) - **router** (object) - The configured router instance with custom search handling. ``` -------------------------------- ### Protecting Authenticated Routes Source: https://tanstack.com/router/latest/docs/guide/authenticated-routes.md Shows how to protect routes by checking authentication status in `beforeLoad` and redirecting to a login page if not authenticated. ```APIDOC ## Protecting Authenticated Routes Then in the authenticated route, you can check the auth state using the `beforeLoad` function, and **throw a `redirect()`** to your **Login route** if the user is not signed-in. <!-- ::start:framework --> # React ```tsx title="src/routes/dashboard.route.tsx" import { createFileRoute, redirect } from '@tanstack/react-router' export const Route = createFileRoute('/dashboard')({ beforeLoad: ({ context, location }) => { if (!context.auth.isAuthenticated) { throw redirect({ to: '/login', search: { redirect: location.href, }, }) } }, }) ``` <!-- ::end:framework --> ``` -------------------------------- ### Implement Complex i18n Routing with Loaders Source: https://tanstack.com/router/latest/docs/guide/path-params.md Demonstrates validation and data fetching using optional locale and category parameters. ```tsx // Route: /{-$locale}/blog/{-$category}/$slug export const Route = createFileRoute('/{-$locale}/blog/{-$category}/$slug')({ beforeLoad: async ({ params }) => { const locale = params.locale || 'en' const category = params.category // Validate locale and category const validLocales = ['en', 'fr', 'es', 'de'] if (locale && !validLocales.includes(locale)) { throw new Error('Invalid locale') } return { locale, category } }, loader: async ({ params, context }) => { const { locale } = context const { slug, category } = params return fetchBlogPost({ slug, category, locale }) }, component: BlogPostComponent, }) function BlogPostComponent() { const { locale, category, slug } = Route.useParams() const data = Route.useLoaderData() return ( <article> <h1>{data.title}</h1> <p> Category: {category || 'All'} | Language: {locale || 'en'} </p> <div>{data.content}</div> </article> ) } ``` ```tsx // Route: /{-$locale}/blog/{-$category}/$slug export const Route = createFileRoute('/{-$locale}/blog/{-$category}/$slug')({ beforeLoad: async ({ params }) => { const locale = params.locale || 'en' const category = params.category // Validate locale and category const validLocales = ['en', 'fr', 'es', 'de'] if (locale && !validLocales.includes(locale)) { throw new Error('Invalid locale') } return { locale, category } }, loader: async ({ params, context }) => { const { locale } = context const { slug, category } = params return fetchBlogPost({ slug, category, locale }) }, component: BlogPostComponent, }) function BlogPostComponent() { const params = Route.useParams() const data = Route.useLoaderData() return ( <article> <h1>{data.title}</h1> <p> Category: {params().category || 'All'} | Language:{' '} {params().locale || 'en'} </p> <div>{data.content}</div> </article> ) } ``` -------------------------------- ### Generate Route Tree Command Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-location.md Command to generate the route tree if not using a supported bundler. Run this command in your project's root directory. ```sh npx tsr generate ``` -------------------------------- ### Define a file route with createFileRoute Source: https://tanstack.com/router/latest/docs/routing/routing-concepts.md Use createFileRoute to define a route path. The path argument is automatically managed by the TanStack Router CLI or Bundler Plugin. ```tsx import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/')({ component: PostsComponent, }) ``` ```tsx import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/')({ component: PostsComponent, }) ``` -------------------------------- ### Preload Route Chunks Manually (React, Solid) Source: https://tanstack.com/router/latest/docs/guide/preloading.md Shows how to use the `loadRouteChunk` method to preload only the JavaScript chunk for a specific route. This is useful for optimizing loading performance by fetching route code ahead of time. It handles multiple route chunks concurrently using `Promise.all` and includes error handling. ```tsx import { useEffect } from 'react' import { useRouter } from '@tanstack/react-router' function Component() { const router = useRouter() useEffect(() => { async function preloadRouteChunks() { try { const postsRoute = router.routesByPath['/posts'] await Promise.all([ router.loadRouteChunk(router.routesByPath['/']), router.loadRouteChunk(postsRoute), router.loadRouteChunk(postsRoute.parentRoute), ]) } catch (err) { // Failed to preload route chunk } } preloadRouteChunks() }, [router]) return <div /> } ``` ```tsx import { createEffect } from 'solid-js' import { useRouter } from '@tanstack/solid-router' function Component() { const router = useRouter() createEffect(() => { async function preloadRouteChunks() { try { const postsRoute = router.routesByPath['/posts'] await Promise.all([ router.loadRouteChunk(router.routesByPath['/']), router.loadRouteChunk(postsRoute), router.loadRouteChunk(postsRoute.parentRoute), ]) } catch (err) { // Failed to preload route chunk } } preloadRouteChunks() }) return <div /> } ``` -------------------------------- ### useLoaderData Hook Reference Source: https://tanstack.com/router/latest/docs/api/router/useLoaderDataHook.md Detailed documentation for the useLoaderData hook, including configuration options and return values. ```APIDOC ## useLoaderData Hook ### Description The `useLoaderData` hook retrieves the loader data from the closest `RouteMatch` in the component tree. ### Options - **from** (string) - Optional - The route ID of the closest parent match. Recommended for full type safety. - **strict** (boolean) - Optional (default: true) - If false, type safety is loosened to reflect shared types of all possible loader data. - **select** (function) - Optional - A selector function `(loaderData: TLoaderData) => TSelected` to transform data and optimize re-renders. - **structuralSharing** (boolean) - Optional - Enables structural sharing for the selected value to optimize rendering. ### Returns - Returns the loader data or the result of the `select` function if provided. ### Usage Example ```tsx import { useLoaderData } from '@tanstack/react-router' function Component() { const loaderData = useLoaderData({ from: '/posts/$postId' }) return <div>{loaderData.body}</div> } ``` ``` -------------------------------- ### Configure Rspack for Solid Source: https://tanstack.com/router/latest/docs/installation/with-rspack.md Add the TanStack Router plugin to your rsbuild.config.ts for Solid projects. ```ts import { defineConfig } from '@rsbuild/core' import { pluginBabel } from '@rsbuild/plugin-babel' import { pluginSolid } from '@rsbuild/plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/rspack' export default defineConfig({ plugins: [ pluginBabel({ include: /\.(?:jsx|tsx)$/, }), pluginSolid(), ], tools: { rspack: { plugins: [tanstackRouter({ target: 'solid', autoCodeSplitting: true })], }, }, }) ``` -------------------------------- ### Code Formatting Options Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md Configure code formatting for generated route files, including quote style, semicolon usage, and route tree formatting. ```APIDOC ### `quoteStyle` When your generated route tree is generated and when you first create a new route, those files will be formatted with the quote style you specify here. By default, this value is set to `single`. > [!TIP] > You should ignore the path of your generated route tree file from your linter and formatter to avoid conflicts. ### `semicolons` When your generated route tree is generated and when you first create a new route, those files will be formatted with semicolons if this option is set to `true`. By default, this value is set to `false`. > [!TIP] > You should ignore the path of your generated route tree file from your linter and formatter to avoid conflicts. ### `enableRouteTreeFormatting` This option turns on the formatting function on the generated route tree file, which can be time-consuming for large projects. By default, this value is set to `true`. ``` -------------------------------- ### Create Authentication Layout Route Source: https://tanstack.com/router/latest/docs/how-to/setup-authentication.md Defines a layout route that checks for authentication status before loading child routes. Throws a redirect to the login page if the user is unauthenticated. ```tsx import { createFileRoute, redirect, Outlet } from '@tanstack/react-router' export const Route = createFileRoute('/_authenticated')({ beforeLoad: ({ context, location }) => { if (!context.auth.isAuthenticated) { throw redirect({ to: '/login', search: { // Save current location for redirect after login redirect: location.href, }, }) } }, component: () => <Outlet />, }) ``` -------------------------------- ### Implement useConditionalNavigate hook Source: https://tanstack.com/router/latest/docs/guide/type-utilities.md A custom hook that wraps useNavigate to provide conditional navigation capabilities based on an internal signal. ```tsx import { createSignal } from 'solid-js' export interface UseConditionalNavigateResult { enable: () => void disable: () => void navigate: () => void } export function useConditionalNavigate< TRouter extends RegisteredRouter = RegisteredRouter, TOptions = unknown, >( navigateOptions: ValidateNavigateOptions<TRouter, TOptions>, ): UseConditionalNavigateResult export function useConditionalNavigate( navigateOptions: ValidateNavigateOptions, ): UseConditionalNavigateResult { const [enabled, setEnabled] = createSignal(false) const navigate = useNavigate() return { enable: () => setEnabled(true), disable: () => setEnabled(false), navigate: () => { if (enabled()) { navigate(navigateOptions) } }, } } ``` -------------------------------- ### Multi-tenant Routing with Rewrites Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Route tenant-specific domains to a unified route structure by extracting the tenant from the subdomain and injecting it into the path, and vice-versa for output. ```tsx const router = createRouter({ routeTree, rewrite: { input: ({ url }) => { // Extract tenant from subdomain: acme.app.com → acme const parts = url.hostname.split('.') if (parts.length >= 3) { const tenant = parts[0] // Inject tenant into the path: /dashboard → /tenant/acme/dashboard url.pathname = `/tenant/${tenant}${url.pathname}` } return url }, output: ({ url }) => { // Extract tenant from path and move to subdomain const match = url.pathname.match(/^\/tenant\/([^/]+)(.*)$/) if (match) { const [, tenant, rest] = match url.hostname = `${tenant}.app.com` url.pathname = rest || '/' } return url }, }, }) ``` -------------------------------- ### Create Admin-Only Protected Route Source: https://tanstack.com/router/latest/docs/how-to/setup-rbac.md Implement an admin-only route using `createFileRoute` and `beforeLoad`. This ensures that only users with the 'admin' role can access the route, redirecting others to an unauthorized page. ```tsx import { createFileRoute, redirect, Outlet } from '@tanstack/react-router' export const Route = createFileRoute('/_authenticated/_admin')({ beforeLoad: ({ context, location }) => { if (!context.auth.hasRole('admin')) { throw redirect({ to: '/unauthorized', search: { redirect: location.href, }, }) } }, component: AdminLayout, }) function AdminLayout() { return ( <div> <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4"> <strong>Admin Area:</strong> You have administrative privileges. </div> <Outlet /> </div> ) } ``` -------------------------------- ### URL Localization via Rewrite Source: https://tanstack.com/router/latest/docs/guide/internationalization-i18n.md Using the router's rewrite configuration to transform URLs bidirectionally, enabling clean localized path prefixes. ```APIDOC ## CONFIGURATION URL Rewrite ### Description Configures the router to automatically localize and de-localize URLs using external i18n runtime functions. ### Method POST (Router Initialization) ### Request Body - **rewrite** (object) - Required - Contains input and output transformation functions. ### Request Example ```ts const router = createRouter({ routeTree, rewrite: { input: ({ url }) => deLocalizeUrl(url), output: ({ url }) => localizeUrl(url), }, }) ``` ``` -------------------------------- ### Basic Optional Parameter Navigation Source: https://tanstack.com/router/latest/docs/guide/navigation.md Shows navigation with, without, and inheriting optional parameters. ```tsx // Navigate with optional parameter <Link to="/posts/{-$category}" params={{ category: 'tech' }} > Tech Posts </Link> // Navigate without optional parameter <Link to="/posts/{-$category}" params={{ category: undefined }} > All Posts </Link> // Navigate using parameter inheritance <Link to="/posts/{-$category}" params={{}} > Current Category </Link> ``` -------------------------------- ### API Reference: `rewrite` option Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Provides details on the `rewrite` option in `createRouter`, its type, and its purpose for configuring bidirectional URL transformation. ```APIDOC ## API Reference ### `rewrite` option - Type: [`LocationRewrite`](#locationrewrite-type) - Optional - Configures bidirectional URL transformation between browser and router. ``` -------------------------------- ### Yarn Workspaces Configuration Source: https://tanstack.com/router/latest/docs/llm-support.md Add this configuration to your `.yarnrc.yaml` file if you are using Yarn Workspaces and TanStack Router to ensure proper integration. ```yaml pnpFallbackMode: all pnpMode: loose ``` -------------------------------- ### Configure addExtensions for ESM Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md Shows how to configure the addExtensions option to replace file extensions in generated imports, which is necessary for certain ESM environments. ```typescript TanStackRouterVite({ addExtensions: 'js', }) ``` -------------------------------- ### React: Zipson Library for JSON Compressed Search Param Serialization Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md Configures TanStack Router in React to use the Zipson library for compressing JSON search parameters. This method offers high performance and excellent compression ratios, requiring binary encoding/decoding. ```tsx import { Router, parseSearchWith, stringifySearchWith, } from '@tanstack/react-router' import { stringify, parse } from 'zipson' const router = createRouter({ parseSearch: parseSearchWith((value) => parse(decodeFromBinary(value))), stringifySearch: stringifySearchWith((value) => encodeToBinary(stringify(value)), ), }) function decodeFromBinary(str: string): string { return decodeURIComponent( Array.prototype.map .call(atob(str), function (c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2) }) .join(''), ) } function encodeToBinary(str: string): string { return btoa( encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) { return String.fromCharCode(parseInt(p1, 16)) }), ) } ``` -------------------------------- ### Define Splat / Catch-All Routes Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md Use a '$' path segment to capture remaining URL segments into the '_splat' key of the params object. ```tsx const filesRoute = createRoute({ getParentRoute: () => rootRoute, path: 'files', }) const fileRoute = createRoute({ getParentRoute: () => filesRoute, path: '$', }) ``` ```js { '_splat': 'documents/hello-world' } ``` -------------------------------- ### Custom Search Serialization Configuration Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md Configuring the router to handle complex search parameter serialization using custom parsing and stringification functions. ```APIDOC ## Configuration: Search Parameter Serialization ### Description This configuration allows developers to define how search parameters are serialized into the URL and parsed back into objects. This is essential for handling complex data structures or compressing URL state. ### Method N/A (Router Configuration) ### Parameters #### Request Body - **parseSearch** (function) - Required - A function that takes a string and returns an object. - **stringifySearch** (function) - Required - A function that takes an object and returns a string. ### Request Example ```tsx const router = createRouter({ parseSearch: parseSearchWith(myParser), stringifySearch: stringifySearchWith(myStringifier), }) ``` ### Response #### Success Response (200) - **router** (object) - The configured router instance with custom search handling. ``` -------------------------------- ### NavigateOptions Interface Source: https://tanstack.com/router/latest/docs/guide/navigation.md The core interface used for all navigation operations in TanStack Router. ```APIDOC ## NavigateOptions Interface ### Description The NavigateOptions interface defines the configuration for performing navigation. It extends ToOptions and includes settings for history management, scrolling, and view transitions. ### Properties - **replace** (boolean) - Optional - Determines whether the navigation should replace the current history entry or push a new one. - **resetScroll** (boolean) - Optional - Determines whether scroll position will be reset to 0,0 after the location is committed to browser history. - **hashScrollIntoView** (boolean | ScrollIntoViewOptions) - Optional - Determines whether an id matching the hash will be scrolled into view. - **viewTransition** (boolean | ViewTransitionOptions) - Optional - Determines if and how the browser will call document.startViewTransition() during navigation. - **ignoreBlocker** (boolean) - Optional - Determines if navigation should ignore any blockers. - **reloadDocument** (boolean) - Optional - Determines if navigation will trigger a full page load. - **href** (string) - Optional - Used in place of 'to' to navigate to a full built href. ``` -------------------------------- ### MatchRoute Component API Source: https://tanstack.com/router/latest/docs/api/router/matchRouteComponent.md API documentation for the MatchRoute component, including props and usage patterns. ```APIDOC ## MatchRoute Component ### Description A component version of the `useMatchRoute` hook that allows for conditional rendering of children based on route matching status. ### Props - **...props** (UseMatchRouteOptions) - Required - Inherits all options from the `useMatchRoute` hook. - **children** (React.ReactNode | (params: TParams | false) => React.ReactNode) - Optional - The content to render. Can be a static node or a function that receives match parameters. ### Usage Example ```tsx import { MatchRoute } from '@tanstack/react-router' function Component() { return ( <div> <MatchRoute to="/posts/$postId" params={{ postId: '123' }} pending> {(match) => <Spinner show={!!match} wait="delay-50" />} </MatchRoute> </div> ) } ``` ``` -------------------------------- ### useParams Hook API Source: https://tanstack.com/router/latest/docs/api/router/useParamsHook.md Detailed documentation for the useParams hook, including configuration options and return values. ```APIDOC ## useParams Hook ### Description The `useParams` hook returns all path parameters parsed for the closest match and its parent matches. ### Parameters #### Options Object - **strict** (boolean) - Optional - Default: true. If false, types are loosened to Partial<AllParams>. - **shouldThrow** (boolean) - Optional - Default: true. If false, returns undefined instead of throwing if no match is found. - **select** (function) - Optional - A selector function to transform the params object and optimize re-renders. - **structuralSharing** (boolean) - Optional - Configures structural sharing for the selected value. ### Returns - Returns an object containing the match's and parent match's path parameters, or the result of the `select` function if provided. ### Usage Example ```tsx import { useParams } from '@tanstack/react-router' function Component() { // Basic usage const params = useParams({ from: '/posts/$postId' }) // Using select for specific param and optimization const postId = useParams({ from: '/posts/$postId', select: (params) => params.postId, }) // Loose typing usage const looseParams = useParams({ strict: false }) } ``` ``` -------------------------------- ### React Route with Head and Localization Source: https://tanstack.com/router/latest/docs/guide/path-params.md Defines a route for a product page with dynamic ID and locale, including SEO head tags and alternate language links. ```tsx export const Route = createFileRoute('/{-$locale}/products/$id')({ component: ProductComponent, head: ({ params, loaderData }) => { const locale = params.locale || 'en' const product = loaderData return { title: product.title[locale] || product.title.en, meta: [ { name: 'description', content: product.description[locale] || product.description.en, }, { property: 'og:locale', content: locale, }, ], links: [ // Canonical URL (always use default locale format) { rel: 'canonical', href: `https://example.com/products/${params.id}`, }, // Alternate language versions { rel: 'alternate', hreflang: 'en', href: `https://example.com/products/${params.id}`, }, { rel: 'alternate', hreflang: 'fr', href: `https://example.com/fr/products/${params.id}`, }, { rel: 'alternate', hreflang: 'es', href: `https://example.com/es/products/${params.id}`, }, ], } }, }) ``` -------------------------------- ### Accessing Search Parameters with Selectors Source: https://tanstack.com/router/latest/docs/guide/render-optimizations.md Demonstrates how to use the select property within useSearch to subscribe to specific subsets of search parameters, preventing unnecessary re-renders when other parameters change. ```tsx const foo = Route.useSearch({ select: ({ foo }) => foo }) ``` -------------------------------- ### Temporary Directory Configuration Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md Configure the temporary directory used for atomic file writes during route generation. ```APIDOC ### `tmpDir` Atomic file writes (route files and the generated route tree file) are implemented by creating a temporary file first and then renaming it to their actual location. This config option allows to configure the path of the temp directory that will be used for creating those temporary files. If it is a relative path, it will be resolved to the current working directory. If this value is not set, `process.env.TSR_TMP_DIR` will be used. If `process.env.TSR_TMP_DIR` is not set, it will default to `.tanstack/tmp` relative to the current working directory. ``` -------------------------------- ### Managing Body Scripts Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md Configure scripts to be rendered in the `<body>` tag using the `scripts` property in `createRootRoute`. ```APIDOC ## Managing Body Scripts ### Description Configure scripts to be rendered in the `<body>` tag using the `scripts` property in `createRootRoute`. This is useful for scripts that require the DOM to be loaded. ### Method N/A (Configuration) ### Endpoint N/A (Configuration) ### Parameters #### Request Body - **scripts** (function) - Required - A function that returns an array of script objects. - **children** (string) - Required - The content of the inline script. - **src** (string) - Optional - The src attribute for an external script. ### Request Example ```tsx export const Route = createRootRoute({ scripts: () => [ { children: 'console.log("Hello, world!")', }, ], }) ``` ### Response N/A (Configuration) ``` -------------------------------- ### beforeLoad Method Source: https://tanstack.com/router/latest/docs/api/router/RouteOptionsType.md The `beforeLoad` method is an asynchronous function executed before a route is loaded. It can be used for authentication checks, redirects, or to prepare route context. If it throws an error, the route loader is skipped, and navigation may be canceled. Returning a promise causes the route to enter a pending state. ```APIDOC ## `beforeLoad` Method ### Description This async function is called before a route is loaded. It's used for pre-route logic like authentication checks or redirects. Errors thrown here prevent the route loader from running and can cancel navigation. Returning a promise suspends rendering until resolution. ### Method `beforeLoad` ### Parameters - **opts** (object) - Required - Options object containing route match details, search params, abort controller, preload status, params, context, location, navigation functions, and cause of execution. - **search** (TFullSearchSchema) - The search schema for the route. - **abortController** (AbortController) - An AbortController instance for canceling operations. - **preload** (boolean) - Indicates if the route is being preloaded. - **params** (TAllParams) - All route parameters. - **context** (TParentContext) - The context from parent routes. - **location** (ParsedLocation) - The current parsed location. - **navigate** (NavigateFn<AnyRoute>) - Deprecated: Function to navigate. - **buildLocation** (BuildLocationFn<AnyRoute>) - Function to build a location object. - **cause** ('enter' | 'stay') - The reason for the `beforeLoad` call ('enter' or 'stay'). ### Return Value - `Promise<TRouteContext>`: If a promise is returned, the route enters a pending state until it resolves. The resolved value is merged into the route's context. - `TRouteContext`: An object to be merged into the route's context. - `void`: If nothing is returned, the function completes without affecting context or state. ### Error Handling - If an error is thrown, the route's loader is not called, and the route does not render. - If thrown during navigation, the navigation is canceled, and the error is passed to `onError`. - If thrown during preload, the error is logged, and preload fails. ### Example Usage ```typescript const route = new Route({ path: '/home', beforeLoad: async ({ search }) => { if (!search.user) { throw redirect({ to: '/login', search: { from: '/home' }, }); } return { message: 'Welcome!' }; }, // ... other route configurations }); ``` > **Note**: The `opts.navigate` function is deprecated. Use `throw redirect({...})` for navigation. ``` -------------------------------- ### Integrate Auth0 Wrapper in App Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Wrap your main application component with the Auth0Wrapper and use the custom hook to access authentication state. This sets up the router context with authentication information. ```tsx import { RouterProvider } from '@tanstack/react-router' import { Auth0Wrapper, useAuth0Context } from './auth/auth0' import { router } from './router' function InnerApp() { const auth = useAuth0Context() if (auth.isLoading) { return ( <div className="flex items-center justify-center min-h-screen"> Loading... </div> ) } return <RouterProvider router={router} context={{ auth }} /> } function App() { return ( <Auth0Wrapper> <InnerApp /> </Auth0Wrapper> ) } export default App ``` -------------------------------- ### Configure virtual routes via CLI Source: https://tanstack.com/router/latest/docs/routing/virtual-file-routes.md Specify the path to a virtual route configuration file or define the structure directly within the tsr.config.json file. ```json // tsr.config.json { "virtualRouteConfig": "./routes.ts" } ``` ```json // tsr.config.json { "virtualRouteConfig": { "type": "root", "file": "root.tsx", "children": [ { "type": "index", "file": "home.tsx" }, { "type": "route", "file": "posts/posts.tsx", "path": "/posts", "children": [ { "type": "index", "file": "posts/posts-home.tsx" }, { "type": "route", "file": "posts/posts-detail.tsx", "path": "$postId" } ] }, { "type": "layout", "id": "first", "file": "layout/first-pathless-layout.tsx", "children": [ { "type": "layout", "id": "second", "file": "layout/second-pathless-layout.tsx", "children": [ { "type": "route", "file": "a.tsx", "path": "/route-a" }, { "type": "route", "file": "b.tsx", "path": "/route-b" } ] } ] } ] } } ``` -------------------------------- ### Configuring Floating Mode Source: https://tanstack.com/router/latest/docs/devtools.md Enable floating mode to mount the devtools as a fixed, toggleable element. The initial state can be controlled via the initialIsOpen prop. ```tsx function App() { return ( <> <RouterProvider router={router} /> <TanStackRouterDevtools initialIsOpen={false} /> </> ); } ``` ```tsx function App() { return ( <> <RouterProvider router={router} /> <TanStackRouterDevtools initialIsOpen={false} /> </> ); } ``` -------------------------------- ### Correct Provider Wrapper Order Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Ensures the authentication provider is correctly wrapped around the `RouterProvider` to make authentication context available in components. ```tsx // ✅ Correct order <AuthProvider> <InnerApp> <RouterProvider /> </InnerApp> </AuthProvider> // ❌ Wrong order <RouterProvider> <AuthProvider /> </RouterProvider> ``` -------------------------------- ### Opt-out of caching with gcTime and shouldReload Source: https://tanstack.com/router/latest/docs/guide/data-loading.md Configure a route to only load on entry or when loader dependencies change by setting gcTime to 0 and shouldReload to false. ```tsx // /routes/posts.tsx export const Route = createFileRoute('/posts')({ loaderDeps: ({ search: { offset, limit } }) => ({ offset, limit }), loader: ({ deps }) => fetchPosts(deps), // Do not cache this route's data after it's unloaded gcTime: 0, // Only reload the route when the user navigates to it or when deps change shouldReload: false, }) ``` -------------------------------- ### Deferred Data Loading with External Libraries Source: https://tanstack.com/router/latest/docs/guide/deferred-data-loading.md When using libraries like TanStack Query, deferred loading is handled by initiating prefetching in the loader without awaiting the result. ```APIDOC ## External Library Integration ### Description For libraries like TanStack Query, do not use the `Await` component. Instead, trigger the fetch in the loader using `prefetchQuery` and access the data via the library's hooks in the component. ### Implementation - **Loader**: Call `queryClient.prefetchQuery` for slow data (do not await) and `queryClient.ensureQueryData` for critical data (await). - **Component**: Use the library's standard hooks (e.g., `useQuery`) to consume the data. ### Example ```tsx // Loader loader: async ({ context: { queryClient } }) => { queryClient.prefetchQuery(slowDataOptions()); await queryClient.ensureQueryData(fastDataOptions()); } ``` ``` -------------------------------- ### Default Route Directory and Generated File Paths Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md Specifies the default directory for route files and the output path for the generated route tree. These paths are relative to the current working directory and are required for the file-based routing to function. The generated route tree file will use a .ts extension by default, but switches to .js if types are disabled. ```txt ./src/routes ``` ```txt ./src/routeTree.gen.ts ``` -------------------------------- ### CatchBoundary Component Source: https://tanstack.com/router/latest/docs/api/router/catchBoundaryComponent.md Demonstrates the usage of the CatchBoundary component with its essential props. ```APIDOC ## CatchBoundary Component ### Description The `CatchBoundary` component is a React component designed to catch errors thrown by its child components. It allows you to render a fallback UI when an error occurs and provides mechanisms for error handling and state resetting. ### Props #### `getResetKey` - **Type**: `() => string` - **Required**: Yes - **Description**: A function that returns a string. When this string changes, the `CatchBoundary`'s internal state is reset. #### `children` - **Type**: `React.ReactNode` - **Required**: Yes - **Description**: The content or components that `CatchBoundary` will render and monitor for errors. #### `errorComponent` - **Type**: `React.ReactNode` - **Optional**: Yes - **Default**: `ErrorComponent` - **Description**: The component to render when an error is caught. If not provided, a default `ErrorComponent` is used. #### `onCatch` - **Type**: `(error: any) => void` - **Optional**: Yes - **Description**: A callback function that is executed when an error is caught. It receives the error object as an argument. ### Returns - Renders `children` if no error occurs. - Renders `errorComponent` if an error is caught. ### Example Usage ```tsx import { CatchBoundary } from '@tanstack/react-router'; function MyComponent() { return ( <CatchBoundary getResetKey={() => 'some-unique-key'} onCatch={(error) => console.error('Caught error:', error)} errorComponent={<div>Custom Error UI</div>} > <div>Content that might throw an error</div> </CatchBoundary> ); } ``` ``` -------------------------------- ### Configure Default Preload Delay Source: https://tanstack.com/router/latest/docs/guide/preloading.md Sets the default delay in milliseconds before preloading begins after a hover or touch event on a link. This helps prevent unnecessary preloads. ```tsx import { createRouter } from '@tanstack/react-router' const router = createRouter({ // ... defaultPreloadDelay: 100, }) ``` ```tsx import { createRouter } from '@tanstack/solid-router' const router = createRouter({ // ... defaultPreloadDelay: 100, }) ``` -------------------------------- ### Create Posts ID Route File Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-location.md Defines a dynamic route for individual posts, identified by `postId`. It includes a loader to fetch specific post data based on the URL parameter. ```tsx // src/routes/posts.$postId.tsx import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/posts/$postId')({ component: PostsId, loader: async ({ params: { postId } }) => { const post = await fetchPost(postId) return { post, } }, }) function PostsId() { const { post } = Route.useLoaderData() // ... } ``` -------------------------------- ### Logging and Route Tree Headers/Footers Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md Control console logging during route generation and define custom headers or footers for the route tree file. ```APIDOC ### `disableLogging` This option turns off the console logging for the route generation process. By default, this value is set to `false`. ### `routeTreeFileHeader` This option let's you prepend content to the start of the generated route tree file. By default, this value is set to: ```json [ "/* eslint-disable */", "// @ts-nocheck", "// noinspection JSUnusedGlobalSymbols" ] ``` ### `routeTreeFileFooter` This option let's you append content to the end of the generated route tree file. By default, this value is set to: ```json [] ``` ``` -------------------------------- ### ViewTransitionOptions Type Source: https://tanstack.com/router/latest/docs/api/router/ViewTransitionOptionsType.md Defines the options for configuring view transitions in the router. ```APIDOC ## ViewTransitionOptions Type ### Description The `ViewTransitionOptions` type is used to define a [viewTransition type](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#view-transition-types). ### Type Definition ```typescript interface ViewTransitionOptions { types: | Array<string> | ((locationChangeInfo: { fromLocation?: ParsedLocation toLocation: ParsedLocation pathChanged: boolean hrefChanged: boolean hashChanged: boolean }) => Array<string> | false) } ``` ### Properties #### `types` Property - **Type**: `Array<string> | ((locationChangeInfo: { fromLocation?: ParsedLocation; toLocation: ParsedLocation; pathChanged: boolean; hrefChanged: boolean; hashChanged: boolean }) => (Array<string> | false))` - **Required**: Yes - **Description**: This property can be either: - An array of strings to be passed to `document.startViewTransition({ update, types })`. - A function that accepts a `locationChangeInfo` object and returns an array of strings for `document.startViewTransition({ update, types })` or `false` to skip the transition. ``` -------------------------------- ### Create a Root Route with Context (React) Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md Define a root route with custom context for React applications, specifying the type of the context object. ```tsx // Root route with Context import { createRootRouteWithContext } from '@tanstack/react-router' import type { QueryClient } from '@tanstack/react-query' export interface MyRouterContext { queryClient: QueryClient } const rootRoute = createRootRouteWithContext<MyRouterContext>() ``` -------------------------------- ### Connect App with Authentication (src/App.tsx) Source: https://tanstack.com/router/latest/docs/how-to/setup-authentication.md Integrates the AuthProvider with the application and provides the authentication context to the router. The InnerApp component consumes the auth state and passes it to the RouterProvider. ```tsx import { RouterProvider } from '@tanstack/react-router' import { AuthProvider, useAuth } from './auth' import { router } from './router' function InnerApp() { const auth = useAuth() return <RouterProvider router={router} context={{ auth }} /> } function App() { return ( <AuthProvider> <InnerApp /> </AuthProvider> ) } export default App ``` -------------------------------- ### Define Optional Parameters with Wildcards Source: https://tanstack.com/router/latest/docs/guide/path-params.md Use optional parameters combined with wildcards to match complex URL structures in React and Solid. ```tsx // Route: /docs/{-$version}/$ // Matches: /docs/extra/path, /docs/v2/extra/path export const Route = createFileRoute('/docs/{-$version}/$')({ component: DocsComponent, }) function DocsComponent() { const { version } = Route.useParams() const { _splat } = Route.useParams() return ( <div> Version: {version || 'latest'} Path: {_splat} </div> ) } ``` ```tsx // Route: /docs/{-$version}/$ // Matches: /docs/extra/path, /docs/v2/extra/path export const Route = createFileRoute('/docs/{-$version}/$')({ component: DocsComponent, }) function DocsComponent() { const params = Route.useParams() return ( <div> Version: {params().version || 'latest'} Path: {params()._splat} </div> ) } ``` -------------------------------- ### Deferred Loading with External Libraries (React) Source: https://tanstack.com/router/latest/docs/guide/deferred-data-loading.md This React snippet shows how to implement deferred data loading when using an external library like TanStack Query. Instead of `defer`, the route loader initiates data fetching using the library's methods (`prefetchQuery`, `ensureQueryData`). Data is then accessed in the component via the library's hooks, allowing the router to render while data is fetched and cached externally. ```tsx import { createFileRoute } from '@tanstack/react-router' import { slowDataOptions, fastDataOptions } from '~/api/query-options' export const Route = createFileRoute('/posts/$postId')({ loader: async ({ context: { queryClient } }) => { // Kick off the fetching of some slower data, but do not await it queryClient.prefetchQuery(slowDataOptions()) // Fetch and await some data that resolves quickly await queryClient.ensureQueryData(fastDataOptions()) }, }) ``` -------------------------------- ### Subscribing to Router Events Source: https://tanstack.com/router/latest/docs/api/router/RouterType.md Demonstrates how to use the .subscribe method to listen for specific router events. It returns an unsubscribe function to prevent memory leaks. ```typescript const unsubscribe = router.subscribe('onResolved', (event) => { console.log('Route resolved:', event); }); // Later, clean up the subscription unsubscribe(); ``` -------------------------------- ### Accessing Route Loader Dependencies with useLoaderDeps Source: https://tanstack.com/router/latest/docs/api/router/useLoaderDepsHook.md Demonstrates how to retrieve loader dependencies using the useLoaderDeps hook. It shows basic usage, route-specific API usage, and the use of the select option to pick specific dependency values. ```tsx import { useLoaderDeps } from '@tanstack/react-router' const routeApi = getRouteApi('/posts/$postId') function Component() { const deps = useLoaderDeps({ from: '/posts/$postId' }) // OR const routeDeps = routeApi.useLoaderDeps() // OR const postId = useLoaderDeps({ from: '/posts', select: (deps) => deps.view, }) } ``` -------------------------------- ### React: JSURL2 Library for Compressed Search Param Serialization Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md Implements search parameter serialization in React using the JSURL2 library for TanStack Router. This method compresses URLs while maintaining readability. ```tsx import { Router, parseSearchWith, stringifySearchWith, } from '@tanstack/react-router' import { parse, stringify } from 'jsurl2' const router = createRouter({ // ... parseSearch: parseSearchWith(parse), stringifySearch: stringifySearchWith(stringify), }) ``` -------------------------------- ### Create Clerk Sign-Up Route Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Defines the route for user sign-up using Clerk's SignUp component. This route should be accessible to new users. ```tsx import { createFileRoute } from '@tanstack/react-router' import { SignUp } from '@clerk/clerk-react' export const Route = createFileRoute('/sign-up')({ component: () => ( <div className="flex items-center justify-center min-h-screen"> <SignUp redirectUrl="/dashboard" signInUrl="/sign-in" /> </div> ), }) ``` -------------------------------- ### Type-safe Menu Items Usage Source: https://tanstack.com/router/latest/docs/guide/type-utilities.md Illustrates the usage of the Menu component with a type-safe array of link options, ensuring all navigation items are correctly configured. ```tsx <Menu items={[ { to: '/posts' }, { to: '/posts/$postId', params: { postId: 'postId' } }, ]} /> ``` -------------------------------- ### createLazyFileRoute Source: https://tanstack.com/router/latest/docs/api/router/createLazyFileRouteFunction.md Defines a lazily loaded file-based route instance for configuring non-critical route properties. ```APIDOC ## createLazyFileRoute(path) ### Description Creates a partial file-based route instance that is lazily loaded when matched. This is used to configure non-critical properties such as component, pendingComponent, errorComponent, and notFoundComponent. ### Parameters #### Path Parameters - **path** (string) - Required - The full path of the file, typically managed automatically by `tsr generate` or `tsr watch`. ### Returns A function that accepts a partial `RouteOptions` object containing properties: component, pendingComponent, errorComponent, and notFoundComponent. ### Request Example ```tsx import { createLazyFileRoute } from '@tanstack/react-router' export const Route = createLazyFileRoute('/')({ component: IndexComponent, }) ``` ### Response Returns a `Route` object instance that must be exported from the file. ``` -------------------------------- ### Binary Encoding Utilities Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md Utility functions to safely encode and decode strings to binary format for URL search parameters. ```APIDOC ## Utility: Binary Encoding/Decoding ### Description Standard `atob` and `btoa` functions may fail with non-UTF8 characters. These utilities provide a safe way to convert strings to binary-encoded strings for URL transport. ### Functions - **encodeToBinary(str: string)**: Encodes a string to a base64-like binary format. - **decodeFromBinary(str: string)**: Decodes the binary format back to the original string. ### Implementation ```ts export function encodeToBinary(str: string): string { return btoa( encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) { return String.fromCharCode(parseInt(p1, 16)); }), ); } export function decodeFromBinary(str: string): string { return decodeURIComponent( Array.prototype.map .call(atob(str), function (c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }) .join(''), ); } ``` ``` -------------------------------- ### Deferred Data Loading with Await Source: https://tanstack.com/router/latest/docs/guide/deferred-data-loading.md This pattern allows rendering critical route data immediately while slower, non-critical data resolves in the background using the Await component. ```APIDOC ## Deferred Data Loading ### Description Use this pattern to defer slow or non-critical data by returning an unawaited promise in the route loader. The application will render the route as soon as awaited promises are resolved. ### Implementation - **Loader**: Return an object containing both awaited (fast) and unawaited (slow) promises. - **Component**: Use the `<Await>` component to handle the resolution of the deferred promise and provide a fallback UI. ### Example ```tsx // Loader loader: async () => { const slowDataPromise = fetchSlowData(); const fastData = await fetchFastData(); return { fastData, deferredSlowData: slowDataPromise }; } // Component <Await promise={deferredSlowData} fallback={<div>Loading...</div>}> {(data) => <div>{data}</div>} </Await> ``` ``` -------------------------------- ### Configure Router Context (src/__root.tsx) Source: https://tanstack.com/router/latest/docs/how-to/setup-authentication.md Defines the root route with a custom context type that includes authentication state. This context will be available throughout the application. ```tsx import { createRootRouteWithContext, Outlet } from '@tanstack/react-router' import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' interface AuthState { isAuthenticated: boolean user: { id: string; username: string; email: string } | null login: (username: string, password: string) => Promise<void> logout: () => void } interface MyRouterContext { auth: AuthState } export const Route = createRootRouteWithContext<MyRouterContext>()({ component: () => ( <div> <Outlet /> <TanStackRouterDevtools /> </div> ), }) ``` -------------------------------- ### Solid: Custom Binary Search Param Serialization Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md Configures TanStack Router in SolidJS to use custom binary encoding and decoding for search parameters. This involves base64 encoding/decoding and URL encoding/decoding to handle complex search objects. ```tsx import { Router, parseSearchWith, stringifySearchWith, } from '@tanstack/solid-router' const router = createRouter({ parseSearch: parseSearchWith((value) => JSON.parse(decodeFromBinary(value))), stringifySearch: stringifySearchWith((value) => encodeToBinary(JSON.stringify(value)), ), }) function decodeFromBinary(str: string): string { return decodeURIComponent( Array.prototype.map .call(atob(str), function (c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2) }) .join(''), ) } function encodeToBinary(str: string): string { return btoa( encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) { return String.fromCharCode(parseInt(p1, 16)) }), ) } ``` -------------------------------- ### Define a Pathless Layout Route Source: https://tanstack.com/router/latest/docs/routing/routing-concepts.md Prefix the route filename with an underscore to create a layout that does not affect the URL path. ```tsx import { Outlet, createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/_pathlessLayout')({ component: PathlessLayoutComponent, }) function PathlessLayoutComponent() { return ( <div> <h1>Pathless layout</h1> <Outlet /> </div> ) } ``` -------------------------------- ### Import TanStack Router Devtools Panel (Solid) Source: https://tanstack.com/router/latest/docs/devtools.md Imports the TanStack Router Devtools Panel component for SolidJS applications. This component is necessary for visualizing router state and debugging. ```tsx import { TanStackRouterDevtoolsPanel } from '@tanstack/solid-router-devtools' ``` -------------------------------- ### File-Based Routing Configuration Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md Configuration options for TanStack Router's file-based routing. ```APIDOC ## File-Based Routing Configuration TanStack Router offers flexible file-based routing with several configuration options. ### Configuration Options - `routesDirectory` (required): Path to the directory containing route files (default: `./src/routes`). - `generatedRouteTree` (required): Path for the generated route tree file (default: `./src/routeTree.gen.ts`). - `virtualRouteConfig`: Configuration for the Virtual File Routes feature. - `routeFilePrefix`: Prefix to identify route files (default: ``). - `routeFileIgnorePrefix`: Prefix to ignore specific files/directories (default: `-`). - `routeFileIgnorePattern`: Regex pattern to ignore files/directories (default: `undefined`). - `indexToken`: Token to identify index routes (default: `index`). - `routeToken`: Token to identify layout routes (default: `route`). - `quoteStyle`: Quote style for generated code (e.g., `single` or `double`). - `semicolons`: Whether to use semicolons in generated code (default: `true`). - `autoCodeSplitting`: Enable automatic code splitting for routes (default: `true`). - `disableTypes`: Disable TypeScript type generation (default: `false`). - `addExtensions`: Add file extensions to generated routes (default: `false`). - `disableLogging`: Disable logging messages (default: `false`). - `routeTreeFileHeader`: Custom header for the generated route tree file. - `routeTreeFileFooter`: Custom footer for the generated route tree file. - `enableRouteTreeFormatting`: Enable formatting for the generated route tree file (default: `true`). - `tmpDir`: Temporary directory for build artifacts (default: `./node_modules/.tanstack-router`). ### `routesDirectory` (required) Specifies the directory where your route files are located, relative to the current working directory. **Default:** ```txt ./src/routes ``` ### `generatedRouteTree` (required) Specifies the file path where the generated route tree will be saved, relative to the current working directory. **Default:** ```txt ./src/routeTree.gen.ts ``` If `disableTypes` is `true`, the file will be saved with a `.js` extension. ### `routeFileIgnorePrefix` This option allows you to ignore specific files and directories within your `routesDirectory` by prefix. Files or directories starting with this prefix will not be considered as routes. **Default:** `-` **Example Usage:** ```txt src/routes ├── posts │ ├── -components // Ignored │ │ ├── Post.tsx │ ├── index.tsx │ ├── route.tsx ``` ### `routeFileIgnorePattern` Use a regular expression to ignore files and directories. This provides more granular control over which files are excluded from routing. **Default:** `undefined` **Example Pattern:** `.((css|const).ts)|test-page` would ignore files like `.css.ts`, `.const.ts`, or directories named `test-page`. ### `routeToken` This token is used to identify layout route files within your `routesDirectory`. Layout routes render child routes within them. **Default:** `route` **Filename Examples:** ```txt src/routes/posts.tsx -> /posts src/routes/posts.route.tsx -> /posts src/routes/posts/route.tsx -> /posts ``` #### Using Regex for `routeToken` You can specify a regular expression for `routeToken` for more flexible matching. **JSON Configuration:** ```json { "routeToken": { "regex": "[a-z]+-layout", "flags": "i" } } ``` **Inline Code Configuration:** ```ts { routeToken: /[a-z]+-layout/i } ``` This allows filenames like `dashboard.main-layout.tsx` or `posts.protected-layout.tsx` to be recognized as layout routes. ``` -------------------------------- ### Define a Child Route with getParentRoute Source: https://tanstack.com/router/latest/docs/decisions-on-dx.md Demonstrates how to manually define a child route using createRoute and specifying the parent route to ensure correct type inference for context and parameters. ```typescript import { createRoute } from '@tanstack/react-router' import { postsRoute } from './postsRoute' export const postsIndexRoute = createRoute({ getParentRoute: () => postsRoute, path: '/', }) ``` -------------------------------- ### Implement Custom UI without Resolver Source: https://tanstack.com/router/latest/docs/guide/navigation-blocking.md Uses the useBlocker hook to return a Promise, allowing for asynchronous custom modal management during navigation attempts. ```tsx import { useBlocker } from '@tanstack/react-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = useState(false) useBlocker({ shouldBlockFn: () => { if (!formIsDirty) return false return new Promise<boolean>((resolve) => { modals.open({ title: 'Are you sure you want to leave?', children: <SaveBlocker confirm={() => { modals.closeAll(); resolve(false) }} reject={() => { modals.closeAll(); resolve(true) }} />, onClose: () => resolve(true), }) }) }, }) } ``` ```tsx import { useBlocker } from '@tanstack/solid-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = createSignal(false) useBlocker({ shouldBlockFn: () => { if (!formIsDirty()) return false return new Promise<boolean>((resolve) => { modals.open({ title: 'Are you sure you want to leave?', children: <SaveBlocker confirm={() => { modals.closeAll(); resolve(false) }} reject={() => { modals.closeAll(); resolve(true) }} />, onClose: () => resolve(true), }) }) }, }) } ``` -------------------------------- ### Create Supabase Authentication Provider Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Implements a React context provider for Supabase authentication. It manages user session, authentication state, and provides login/logout functions. ```tsx import { createClient } from '@supabase/supabase-js' import { createContext, useContext, useEffect, useState } from 'react' const supabase = createClient( import.meta.env.VITE_SUPABASE_URL, import.meta.env.VITE_SUPABASE_ANON_KEY, ) interface SupabaseAuthState { isAuthenticated: boolean user: any login: (email: string, password: string) => Promise<void> logout: () => Promise<void> isLoading: boolean } const SupabaseAuthContext = createContext<SupabaseAuthState | undefined>( undefined, ) export function SupabaseAuthProvider({ children, }: { children: React.ReactNode }) { const [user, setUser] = useState(null) const [isAuthenticated, setIsAuthenticated] = useState(false) const [isLoading, setIsLoading] = useState(true) useEffect(() => { // Get initial session supabase.auth.getSession().then(({ data: { session } }) => { setUser(session?.user ?? null) setIsAuthenticated(!!session?.user) setIsLoading(false) }) // Listen for auth changes const { data: { subscription }, } = supabase.auth.onAuthStateChange((_event, session) => { setUser(session?.user ?? null) setIsAuthenticated(!!session?.user) setIsLoading(false) }) return () => subscription.unsubscribe() }, []) const login = async (email: string, password: string) => { const { error } = await supabase.auth.signInWithPassword({ email, password, }) if (error) throw error } const logout = async () => { const { error } = await supabase.auth.signOut() if (error) throw error } return ( <SupabaseAuthContext.Provider value={{ isAuthenticated, user, login, logout, isLoading, }}> {children} </SupabaseAuthContext.Provider> ) } export function useSupabaseAuth() { const context = useContext(SupabaseAuthContext) if (context === undefined) { throw new Error('useSupabaseAuth must be used within SupabaseAuthProvider') } return context } ``` -------------------------------- ### Use QueryClient in Route Loader Source: https://tanstack.com/router/latest/docs/guide/router-context.md Utilizes the QueryClient from the router context to ensure data is fetched. ```tsx // src/routes/todos.tsx export const Route = createFileRoute('/todos')({ component: Todos, loader: async ({ context }) => { await context.queryClient.ensureQueryData({ queryKey: ['todos', { userId: user.id }], queryFn: fetchTodos, }) }, }) ``` -------------------------------- ### Configure Route Head Metadata Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md Define route-specific metadata including title, meta tags, links, styles, and scripts using the head property in createRootRoute. ```tsx export const Route = createRootRoute({ head: () => ({ meta: [ { name: 'description', content: 'My App is a web application' }, { title: 'My App' }, ], links: [{ rel: 'icon', href: '/favicon.ico' }], styles: [{ media: 'all and (max-width: 500px)', children: `p { color: blue; background-color: yellow; }`, }], scripts: [{ src: 'https://www.google-analytics.com/analytics.js' }], }), }) ``` -------------------------------- ### Access Path Params in Loader Source: https://tanstack.com/router/latest/docs/guide/path-params.md Demonstrates how path parameters are passed to the `loader` function as a `params` object. The `postId` is accessible for fetching data. ```tsx export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params }) => { return fetchPost(params.postId) }, }) ``` -------------------------------- ### Link Component Usage Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Demonstrates how the Link component automatically applies output rewrites to href attributes, such as adding locale prefixes. ```APIDOC ## Link Component The `<Link>` component automatically applies output rewrites when generating `href` attributes: ### Request Example ```tsx // With locale rewrite configured (adds /en prefix) <Link to="/about">About</Link> // Renders: <a href="/en/about">About</a> ``` ``` -------------------------------- ### NavigateOptions Interface Source: https://tanstack.com/router/latest/docs/guide/navigation.md Defines the core options for performing navigation, extending ToOptions with history and scroll behavior controls. ```ts export type NavigateOptions< TRouteTree extends AnyRoute = AnyRoute, TFrom extends RoutePaths<TRouteTree> | string = string, TTo extends string = '', > = ToOptions<TRouteTree, TFrom, TTo> & { // `replace` is a boolean that determines whether the navigation should replace the current history entry or push a new one. replace?: boolean // `resetScroll` is a boolean that determines whether scroll position will be reset to 0,0 after the location is committed to browser history. resetScroll?: boolean // `hashScrollIntoView` is a boolean or object that determines whether an id matching the hash will be scrolled into view after the location is committed to history. hashScrollIntoView?: boolean | ScrollIntoViewOptions // `viewTransition` is either a boolean or function that determines if and how the browser will call document.startViewTransition() when navigating. viewTransition?: boolean | ViewTransitionOptions // `ignoreBlocker` is a boolean that determines if navigation should ignore any blockers that might prevent it. ignoreBlocker?: boolean // `reloadDocument` is a boolean that determines if navigation to a route inside of router will trigger a full page load instead of the traditional SPA navigation. reloadDocument?: boolean // `href` is a string that can be used in place of `to` to navigate to a full built href, e.g. pointing to an external target. href?: string } ``` -------------------------------- ### Implement Breadcrumbs with Static Data Source: https://tanstack.com/router/latest/docs/guide/static-route-data.md Demonstrates using static data functions to generate dynamic breadcrumb titles. ```tsx export const Route = createFileRoute('/posts/$postId')({ staticData: { getTitle: () => 'Post Details' }, }) ``` -------------------------------- ### Link Component Active Options Source: https://tanstack.com/router/latest/docs/guide/navigation.md Explains the `activeOptions` prop for the Link component, which allows customization of how the active state is determined. ```APIDOC ## Link Component Active Options ### Description The `Link` component provides an `activeOptions` prop to customize the logic for determining if a link is active. ### Interface: ActiveOptions ```typescript export interface ActiveOptions { // If true, the link will be active if the current route matches the `to` route path exactly (no children routes) // Defaults to `false` exact?: boolean // If true, the link will only be active if the current URL hash matches the `hash` prop // Defaults to `false` includeHash?: boolean // Defaults to false // If true, the link will only be active if the current URL search params inclusively match the `search` prop // Defaults to `true` includeSearch?: boolean // This modifies the `includeSearch` behavior. // If true, properties in `search` that are explicitly `undefined` must NOT be present in the current URL search params for the link to be active. // defaults to `false` explicitUndefined?: boolean } ``` ### Default Behavior By default, the `Link` component checks if the resulting **pathname** is a prefix of the current route. If search params are provided, it checks for inclusive matching. Hashes are not checked by default. ### Examples **Default active links:** ```tsx const link1 = ( <Link to="/blog/post/$postId" params={{ postId: 'my-first-blog-post' }}> Blog Post </Link> ) const link2 = <Link to="/blog/post">Blog Post</Link> const link3 = <Link to="/blog">Blog Post</Link> ``` **Inactive link example:** ```tsx const link4 = ( <Link to="/blog/post/$postId" params={{ postId: 'my-second-blog-post' }}> Blog Post </Link> ) ``` **Exact match for home page:** ```tsx const link = ( <Link to="/" activeOptions={{ exact: true }}> Home </Link> ) ``` **Additional Options:** - `includeHash: true`: Include the URL hash in the matching. - `includeSearch: false`: Exclude search parameters from the matching. ``` -------------------------------- ### Combine Prefixes with Wildcards Source: https://tanstack.com/router/latest/docs/guide/path-params.md Uses a static prefix with a wildcard route to capture complex path structures. ```tsx export const Route = createFileRoute('/on-disk/storage-{$postId}/$')({ component: StorageComponent, }) function StorageComponent() { const { _splat } = Route.useParams() // _splat, will be value after 'storage-' // i.e. my-drive/documents/foo.txt return <div>Storage Location: /{_splat}</div> } ``` ```tsx export const Route = createFileRoute('/on-disk/storage-{$postId}/$')({ component: StorageComponent, }) function StorageComponent() { const params = Route.useParams() // _splat, will be value after 'storage-' // i.e. my-drive/documents/foo.txt return <div>Storage Location: /{params()._splat}</div> } ``` -------------------------------- ### Configure 404 Not Found Route Source: https://tanstack.com/router/latest/docs/guide/creating-a-router.md Adds a notFoundComponent to the root route configuration to handle unmatched paths. ```tsx export const Route = createRootRoute({ component: () => ( // ... ), notFoundComponent: () => <div>404 Not Found</div>, }); ``` -------------------------------- ### Composing Multiple Rewrites Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Combine multiple independent rewrite transformations using `composeRewrites`. Input rewrites execute in order, and output rewrites execute in reverse order. ```tsx import { composeRewrites } from '@tanstack/react-router' const localeRewrite = { input: ({ url }) => { // Strip locale prefix const match = url.pathname.match(/^\/(en|fr|es)(\/.*)$/) if (match) { url.pathname = match[2] || '/' } return url }, output: ({ url }) => { // Add locale prefix url.pathname = `/en${url.pathname === '/' ? '' : url.pathname}` return url }, } const legacyRewrite = { input: ({ url }) => { if (url.pathname === '/old-page') { url.pathname = '/new-page' } return url }, } const router = createRouter({ routeTree, rewrite: composeRewrites([localeRewrite, legacyRewrite]), }) ``` -------------------------------- ### Combine Suffixes with Wildcards Source: https://tanstack.com/router/latest/docs/guide/path-params.md Uses a static suffix with a wildcard to match files with specific extensions. ```tsx export const Route = createFileRoute('/files/{$}.txt')({ component: FileComponent, }) function FileComponent() { const { _splat } = Route.useParams() // _splat will be the value before '.txt' return <div>File Splat: {_splat}</div> } ``` ```tsx export const Route = createFileRoute('/files/{$}.txt')({ component: FileComponent, }) function FileComponent() { const params = Route.useParams() // _splat will be the value before '.txt' return <div>File Splat: {params()._splat}</div> } ``` -------------------------------- ### Custom Search Serialization Configuration Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md Configuring the TanStack Router instance to use custom parseSearch and stringifySearch functions with binary encoding. ```APIDOC ## Configuration: Custom Search Serialization ### Description This configuration allows for compressed and binary-safe search parameter handling in TanStack Router. It uses `zipson` for data compression and custom binary encoding to ensure URL compatibility. ### Implementation - **parseSearch**: Uses `parseSearchWith` combined with a custom binary decoder and `zipson.parse`. - **stringifySearch**: Uses `stringifySearchWith` combined with `zipson.stringify` and a custom binary encoder. ### Code Example ```tsx import { Router, parseSearchWith, stringifySearchWith } from '@tanstack/solid-router'; import { stringify, parse } from 'zipson'; const router = createRouter({ parseSearch: parseSearchWith((value) => parse(decodeFromBinary(value))), stringifySearch: stringifySearchWith((value) => encodeToBinary(stringify(value))), }); ``` ``` -------------------------------- ### Define a virtual route tree Source: https://tanstack.com/router/latest/docs/routing/virtual-file-routes.md Use the @tanstack/virtual-file-routes package to map a route tree to specific files in the project. ```tsx // routes.ts import { rootRoute, route, index, layout, physical, } from '@tanstack/virtual-file-routes' export const routes = rootRoute('root.tsx', [ index('index.tsx'), layout('pathlessLayout.tsx', [ route('/dashboard', 'app/dashboard.tsx', [ index('app/dashboard-index.tsx'), route('/invoices', 'app/dashboard-invoices.tsx', [ index('app/invoices-index.tsx'), route('$id', 'app/invoice-detail.tsx'), ]), ]), physical('/posts', 'posts'), ]), ]) ``` -------------------------------- ### Enforcing Route Property Order in TanStack Router Source: https://tanstack.com/router/latest/docs/eslint/create-route-property-order.md Demonstrates the correct property order for route definitions. By placing 'beforeLoad' before 'loader', the context is correctly inferred for subsequent route operations. ```tsx /* eslint "@tanstack/router/create-route-property-order": "warn" */ import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/path')({ beforeLoad: () => ({ hello: 'world' }), loader: async ({ context }) => { await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) }, }) ``` ```tsx /* eslint "@tanstack/router/create-route-property-order": "warn" */ import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/path')({ beforeLoad: () => ({ hello: 'world' }), loader: async ({ context }) => { await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) }, }) ``` -------------------------------- ### Solid Root Layout and Routes Source: https://tanstack.com/router/latest/docs/installation/manual.md Defines the root layout component with navigation links and outlets for child routes in a Solid application. Includes index and about route components. ```tsx import { createRootRoute, Link, Outlet } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' const RootLayout = () => ( <> <div class="p-2 flex gap-2"> <Link to="/" class="[&.active]:font-bold"> Home </Link>{' '} <Link to="/about" class="[&.active]:font-bold"> About </Link> </div> <hr /> <Outlet /> <TanStackRouterDevtools /> </> ) export const Route = createRootRoute({ component: RootLayout }) ``` ```tsx import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/')({ component: Index, }) function Index() { return ( <div class="p-2"> <h3>Welcome Home!</h3> </div> ) } ``` ```tsx import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/about')({ component: About, }) function About() { return <div class="p-2">Hello from About!</div> } ``` -------------------------------- ### ClientOnly Component API Source: https://tanstack.com/router/latest/docs/api/router/clientOnlyComponent.md Usage and prop documentation for the ClientOnly component. ```APIDOC ## ClientOnly Component ### Description The `ClientOnly` component is used to render a component only in the client, without breaking the server-side rendering due to hydration errors. It accepts a `fallback` prop that will be rendered if the JS is not yet loaded in the client. ### Props - **fallback** (ReactNode) - Optional - The component to render if the JS is not yet loaded in the client. - **children** (ReactNode) - Required - The component to render if the JS is loaded in the client. ### Returns - Returns the component's children if the JS is loaded in the client. - Returns the `fallback` component if the JS is not yet loaded in the client. ### Usage Example ```tsx import { ClientOnly } from '@tanstack/react-router' function Dashboard() { return ( <ClientOnly fallback={<FallbackCharts />}> <Charts /> </ClientOnly> ) } ``` ``` -------------------------------- ### Link Component Preloading Source: https://tanstack.com/router/latest/docs/guide/navigation.md Explains the route preloading feature of the Link component, which enhances perceived performance by prefetching route data on user intent. ```APIDOC ## Link Component Preloading ### Description The `Link` component supports automatic route preloading based on user intent (e.g., hovering or touchstart). This feature can be configured globally in router options or per-link using the `preload` prop. ### Usage Set the `preload` prop to `'intent'` to enable preloading on hover or touch. ### Example ```tsx const link = ( <Link to="/blog/post/$postId" preload="intent"> Blog Post </Link> ) ``` ### Benefits Preloading can significantly improve perceived performance, especially when combined with cache-first data fetching libraries like `@tanstack/query`, by making routes ready for a stale-while-revalidate experience. ``` -------------------------------- ### Subscribe to Router Events (TypeScript/React) Source: https://tanstack.com/router/latest/docs/guide/router-events.md Demonstrates basic usage of `router.subscribe` to listen for the 'onResolved' event. It logs navigation completion details and returns an unsubscribe function for cleanup. ```tsx const unsubscribe = router.subscribe('onResolved', (event) => { console.info('Navigation finished:', event.toLocation.href) }) // Later, clean up the listener unsubscribe() ``` -------------------------------- ### Create Login Route Source: https://tanstack.com/router/latest/docs/how-to/setup-authentication.md Handles user credentials and redirects to the intended destination upon successful authentication. Validates search parameters to manage post-login navigation. ```tsx import { createFileRoute, redirect } from '@tanstack/react-router' import { useState } from 'react' export const Route = createFileRoute('/login')({ validateSearch: (search) => ({ redirect: (search.redirect as string) || '/', }), beforeLoad: ({ context, search }) => { // Redirect if already authenticated if (context.auth.isAuthenticated) { throw redirect({ to: search.redirect }) } }, component: LoginComponent, }) function LoginComponent() { const { auth } = Route.useRouteContext() const { redirect } = Route.useSearch() const navigate = Route.useNavigate() const [username, setUsername] = useState('') const [password, setPassword] = useState('') const [isLoading, setIsLoading] = useState(false) const [error, setError] = useState('') const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() setIsLoading(true) setError('') try { await auth.login(username, password) // Navigate to the redirect URL using router navigation navigate({ to: redirect }) } catch (err) { setError('Invalid username or password') } finally { setIsLoading(false) } } return ( <div className="min-h-screen flex items-center justify-center"> <form onSubmit={handleSubmit} className="max-w-md w-full space-y-4 p-6 border rounded-lg" > <h1 className="text-2xl font-bold text-center">Sign In</h1> {error && ( <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded"> {error} </div> )} <div> <label htmlFor="username" className="block text-sm font-medium mb-1"> Username </label> <input id="username" type="text" value={username} onChange={(e) => setUsername(e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required /> </div> <div> <label htmlFor="password" className="block text-sm font-medium mb-1"> Password </label> <input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required /> </div> <button type="submit" disabled={isLoading} className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed" > {isLoading ? 'Signing in...' : 'Sign In'} </button> </form> </div> ) } ``` -------------------------------- ### Define a File-Based Route in TanStack Router Source: https://tanstack.com/router/latest/docs/decisions-on-dx.md This snippet demonstrates how to define a route using the createFileRoute helper. The TanStack Router Bundler Plugin automatically handles the code-splitting and registration of this component. ```tsx import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/posts/')({ component: () => 'Posts index component goes here!!!', }) ``` -------------------------------- ### TypeScript Configuration for SolidJS Source: https://tanstack.com/router/latest/docs/installation/with-router-cli.md Configure your tsconfig.json for SolidJS projects when using TypeScript to ensure proper JSX handling. ```json { "compilerOptions": { "jsx": "preserve", "jsxImportSource": "solid-js" } } ``` -------------------------------- ### Configure TanStackRouter plugin with external route file Source: https://tanstack.com/router/latest/docs/routing/virtual-file-routes.md Pass the path of the routes file to the virtualRouteConfig option in the plugin configuration. ```tsx // vite.config.ts import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' export default defineConfig({ plugins: [ tanstackRouter({ target: 'react', virtualRouteConfig: './routes.ts', }), react(), ], }) ``` ```tsx // vite.config.ts import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/vite' export default defineConfig({ plugins: [ tanstackRouter({ target: 'solid', virtualRouteConfig: './routes.ts', }), solid(), ], }) ``` -------------------------------- ### Stitch Routes into a Route Tree Source: https://tanstack.com/router/latest/docs/decisions-on-dx.md Shows how to manually assemble individual route objects into a hierarchical route tree structure required by the router instance. ```typescript const routeTree = rootRoute.addChildren([ postsRoute.addChildren([postsIndexRoute, postsIdRoute]), ]) ``` -------------------------------- ### Define Optional Path Parameters Source: https://tanstack.com/router/latest/docs/routing/routing-concepts.md Use '{-$paramName}' syntax to define segments that are optional in the URL path. ```tsx // The `-$category` segment is optional, so this route matches both `/posts` and `/posts/tech` import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/posts/{-$category}')({ component: PostsComponent, }) function PostsComponent() { const { category } = Route.useParams() return <div>{category ? `Posts in ${category}` : 'All Posts'}</div> } ``` ```tsx // The `-$category` segment is optional, so this route matches both `/posts` and `/posts/tech` import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/posts/{-$category}')({ component: PostsComponent, }) function PostsComponent() { const { category } = Route.useParams() return <div>{category ? `Posts in ${category()}` : 'All Posts'}</div> } ``` -------------------------------- ### getRouteApi().redirect Source: https://tanstack.com/router/latest/docs/api/router/redirectFunction.md Shows how to access and use the redirect functionality outside of route definition files using `getRouteApi` for type-safe redirects. ```APIDOC ## getRouteApi().redirect ### Description Allows access to the redirect method from outside the route definition file, providing type-safe redirects with an automatically inferred origin path. ### Method `getRouteApi(routePath).redirect(options: RedirectOptions)` ### Endpoint N/A (Used within callbacks or functions) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (RedirectOptions) - Required - Options to determine the redirect behavior. - **to** (string) - Required - The relative or absolute route path to redirect to. - **throw** (boolean) - Optional - If true, the `Redirect` object will be thrown. Defaults to true when used in `beforeLoad` or `loader`. ### Request Example ```tsx import { getRouteApi } from '@tanstack/react-router' const routeApi = getRouteApi('/dashboard/settings') // In a beforeLoad or loader callback function checkAuth() { if (!user) { // Type-safe redirect with automatic 'from' parameter throw routeApi.redirect({ to: '../login', }) } } ``` ### Response #### Success Response (200) N/A (This function triggers a redirect, not a typical response) #### Response Example N/A ``` -------------------------------- ### Match Route Source: https://tanstack.com/router/latest/docs/api/router/RouterType.md Matches a pathname and search params against the router's route tree to find route parameters or determine if a match exists. ```APIDOC ## .matchRoute method Matches a pathname and search params against the router's route tree and returns a route match's params or false if no match was found. ### Method `matchRoute` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **dest** (ToOptions) - Required - The destination to match against. - **matchOpts** (MatchRouteOptions) - Optional - Options that will be used to match the destination. ### Request Example ```json { "dest": { "to": "/users" }, "matchOpts": { "caseSensitive": true } } ``` ### Response #### Success Response (200) - **params** (object) - A route match's params if a match was found. #### Error Response - **false** - If no match was found. #### Response Example ```json { "userId": "123" } ``` ```json false ``` ``` -------------------------------- ### useNavigate Hook Source: https://tanstack.com/router/latest/docs/guide/navigation.md The useNavigate hook provides a function for imperative navigation, typically used for side-effect navigations like after an async action. ```APIDOC ## useNavigate ### Description Returns a navigate function to perform imperative navigation. Recommended for side-effects where the Link component is not suitable. ### Parameters - **from** (string) - Optional - The route to navigate from, used to provide context for relative navigation. ### Request Example const navigate = useNavigate({ from: '/posts/$postId' }); navigate({ to: '/posts/$postId', params: { postId: '123' } }); ``` -------------------------------- ### Access Path Params in beforeLoad Source: https://tanstack.com/router/latest/docs/guide/path-params.md Shows how to access path parameters within the `beforeLoad` function, allowing pre-processing or validation before route loading. ```tsx export const Route = createFileRoute('/posts/$postId')({ beforeLoad: async ({ params }) => { // do something with params.postId }, }) ``` -------------------------------- ### Implement RouterClient in React Source: https://tanstack.com/router/latest/docs/guide/ssr.md Use RouterClient in the client entry point to render the application and handle hydration. ```jsx <RouterClient router={router} /> ``` -------------------------------- ### createLink with React Aria Components Source: https://tanstack.com/router/latest/docs/guide/custom-link.md Shows how to integrate `createLink` with React Aria Components (RAC) to create custom links that leverage RAC's features like render props and accessibility. ```APIDOC ## createLink with React Aria Components ### Description This section details how to use `createLink` with React Aria Components (v1.11.0+). It demonstrates wrapping RAC components like `Link` and `MenuItem` to enable TanStack Router's `preload` functionality and custom styling. ### Method N/A (This is a component creation example) ### Endpoint N/A ### Parameters N/A ### Request Example #### RACLink.tsx ```tsx import { createLink } from '@tanstack/react-router'; import { Link as RACLink, MenuItem } from 'react-aria-components'; export const Link = createLink(RACLink); export const MenuItemLink = createLink(MenuItem); ``` #### CustomRACLink.tsx ```tsx import { createLink } from '@tanstack/react-router'; import { Link as RACLink, type LinkProps } from 'react-aria-components'; interface MyLinkProps extends LinkProps { // your props } function MyLink(props: MyLinkProps) { return ( <RACLink {...props} style={({ isHovered }) => ({ color: isHovered ? 'red' : 'blue', })} /> ); } export const Link = createLink(MyLink); ``` ### Response N/A (This is a component creation example) ``` -------------------------------- ### Access Static Data via Matches Source: https://tanstack.com/router/latest/docs/guide/static-route-data.md Shows how to retrieve static data from route matches within a root component. ```tsx const matches = useMatches() return ( <div> {matches.map((match) => ( <div key={match.id}>{match.staticData.customData}</div> ))} </div> ) ``` ```tsx const matches = useMatches() return ( <div> <For each={matches()}> {(match) => <div>{match.staticData.customData}</div>} </For> </div> ) ``` -------------------------------- ### Link Component Preloading Delay Source: https://tanstack.com/router/latest/docs/guide/navigation.md Details the `preloadDelay` prop for the Link component, allowing customization of the delay before intent-based route preloading is triggered. ```APIDOC ## Link Component Preloading Delay ### Description Controls the delay before intent-based preloading is triggered for a `Link` component. The default delay is 50 milliseconds. ### Usage Pass the `preloadDelay` prop with a number of milliseconds to customize the delay. ### Example ```tsx const link = ( <Link to="/blog/post/$postId" preload="intent" preloadDelay={100}> Blog Post </Link> ) ``` ``` -------------------------------- ### Configuring Path Parameter Encoding Source: https://tanstack.com/router/latest/docs/api/router/linkComponent.md Shows how to handle special characters in URL parameters. By default, characters like '@' are encoded, but this can be customized via the router configuration. ```tsx // url path will be `/%40foo` <Link to="/$username" params={{ username: '@foo' }} /> ``` ```typescript import { createRouter } from '@tanstack/react-router' const router = createRouter({ routeTree, pathParamsAllowedCharacters: ['@'], }) ``` -------------------------------- ### createRootRouteWithContext Function Source: https://tanstack.com/router/latest/docs/api/router/createRootRouteWithContextFunction.md This snippet demonstrates how to use the createRootRouteWithContext function to define a root route with a specific router context type. ```APIDOC ## createRootRouteWithContext ### Description The `createRootRouteWithContext` function is a helper function that can be used to create a root route instance that requires a context type to be fulfilled when the router is created. ### Generics - `TRouterContext`: The context type that will be required to be fulfilled when the router is created. Optional, but recommended. ### Returns - A factory function that can be used to create a new `createRootRoute` instance. It accepts a single argument, the same as the `createRootRoute` function. ### Example ```tsx import { createRootRouteWithContext, createRouter, } from '@tanstack/react-router' import { QueryClient } from '@tanstack/react-query' interface MyRouterContext { queryClient: QueryClient } const rootRoute = createRootRouteWithContext<MyRouterContext>()({ component: () => <Outlet />, // ... root route options }) const routeTree = rootRoute.addChildren([ // ... other routes ]) const queryClient = new QueryClient() const router = createRouter({ routeTree, context: { queryClient, }, }) ``` ``` -------------------------------- ### Render Application on Server with renderRouterToString Source: https://tanstack.com/router/latest/docs/guide/ssr.md Provides a custom render handler using renderRouterToString for more control over the server response. ```tsx import { createRequestHandler, renderRouterToString, RouterServer, } from '@tanstack/react-router/ssr/server' import { createRouter } from './router' export function render({ request }: { request: Request }) { const handler = createRequestHandler({ request, createRouter }) return handler(({ request, responseHeaders, router }) => renderRouterToString({ request, responseHeaders, router, children: <RouterServer router={router} />, }), ) } ``` ```tsx import { createRequestHandler, renderRouterToString, RouterServer, } from '@tanstack/react-router/ssr/server' import { createRouter } from './router' export function render({ request }: { request: Request }) { const handler = createRequestHandler({ request, createRouter }) return handler(({ request, responseHeaders, router }) => renderRouterToString({ request, responseHeaders, router, children: <RouterServer router={router} />, }), ) } ``` -------------------------------- ### Implement Time-Based Permissions Source: https://tanstack.com/router/latest/docs/how-to/setup-rbac.md Validate permissions against time-restricted strings formatted as permission:time:startHour:endHour. ```tsx function hasTimeBasedPermission(auth: AuthState, permission: string) { const userPermissions = auth.user?.permissions || [] const hasPermission = userPermissions.includes(permission) // Check if permission has time restrictions const timeRestricted = userPermissions.find((p) => p.startsWith(`${permission}:time:`), ) if (timeRestricted) { const [, , startHour, endHour] = timeRestricted.split(':') const currentHour = new Date().getHours() return ( currentHour >= parseInt(startHour) && currentHour <= parseInt(endHour) ) } return hasPermission } ``` -------------------------------- ### Type-safe Link Options Usage Source: https://tanstack.com/router/latest/docs/guide/type-utilities.md Demonstrates how to use the HeadingLink component with type-safe link options, ensuring correct parameters and search values. ```tsx <HeadingLink title="Posts" linkOptions={{ to: '/posts' }} /> <HeadingLink title="Post" linkOptions={{ to: '/posts/$postId', params: {postId: 'postId'} }} /> ``` -------------------------------- ### Implement Streaming SSR with renderRouterToStream Source: https://tanstack.com/router/latest/docs/guide/ssr.md Use renderRouterToStream for more granular control over the streaming process. ```tsx import { createRequestHandler, renderRouterToStream, RouterServer, } from '@tanstack/react-router/ssr/server' import { createRouter } from './router' export function render({ request }: { request: Request }) { const handler = createRequestHandler({ request, createRouter }) return handler(({ request, responseHeaders, router }) => renderRouterToStream({ request, responseHeaders, router, children: <RouterServer router={router} />, }), ) } ``` ```tsx import { createRequestHandler, renderRouterToStream, RouterServer, } from '@tanstack/solid-router/ssr/server' import { createRouter } from './router' export function render({ request }: { request: Request }) { const handler = createRequestHandler({ request, createRouter }) return handler(({ request, responseHeaders, router }) => renderRouterToStream({ request, responseHeaders, router, children: <RouterServer router={router} />, }), ) } ``` -------------------------------- ### Implement Resource-Based Permissions Source: https://tanstack.com/router/latest/docs/how-to/setup-rbac.md Define logic to check access against specific resource ownership and roles, then apply it within route components. ```tsx // Check if user can edit a specific resource function canEditResource(auth: AuthState, resourceId: string, ownerId: string) { // Admin can edit anything if (auth.hasRole('admin')) return true // Owner can edit their own resources if (auth.user?.id === ownerId && auth.hasPermission('resource:edit:own')) return true // Moderators can edit with permission if (auth.hasRole('moderator') && auth.hasPermission('resource:edit:any')) return true return false } // Usage in component function ResourceEditor({ resource }) { const { auth } = Route.useRouteContext() if (!canEditResource(auth, resource.id, resource.ownerId)) { return <div>You cannot edit this resource</div> } return <EditForm resource={resource} /> } ``` -------------------------------- ### Create relative links Source: https://tanstack.com/router/latest/docs/guide/navigation.md Navigation relative to a specific route path using the from prop. ```tsx const postIdRoute = createRoute({ path: '/blog/post/$postId', }) const link = ( <Link from={postIdRoute.fullPath} to="../categories"> Categories </Link> ) ``` -------------------------------- ### API Reference: `LocationRewrite` type Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Defines the `LocationRewrite` type, specifying the optional `input` and `output` functions for transforming URLs. ```APIDOC ### `LocationRewrite` type ```tsx type LocationRewrite = { /** * Transform the URL before the router interprets it. * Called when reading from browser history. */ input?: LocationRewriteFunction /** * Transform the URL before it's written to browser history. * Called when generating links and committing navigation. */ output?: LocationRewriteFunction } ``` ``` -------------------------------- ### Preload Data in Route Loader with TanStack Query (React) Source: https://tanstack.com/router/latest/docs/integrations/query.md Preload critical data in a route's loader using `ensureQueryData` to avoid waterfalls. This ensures server-fetched data is dehydrated and streamed to the client during SSR. Prefer `useSuspenseQuery` in the component for optimal SSR and streaming. ```tsx import { queryOptions, useSuspenseQuery, useQuery } from '@tanstack/react-query' import { createFileRoute } from '@tanstack/react-router' const postsQuery = queryOptions({ queryKey: ['posts'], queryFn: () => fetch('/api/posts').then((r) => r.json()), }) export const Route = createFileRoute('/posts')({ // Ensure the data is in the cache before render loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), component: PostsPage, }) function PostsPage() { // Prefer suspense for best SSR + streaming behavior const { data } = useSuspenseQuery(postsQuery) return <div>{data.map((p: any) => p.title).join(', ')}</div> } ``` -------------------------------- ### Optional Path Parameter Routing Source: https://tanstack.com/router/latest/docs/guide/internationalization-i18n.md Implementing locale-aware routing using TanStack Router's optional path parameter syntax to support multiple locales without duplicating route definitions. ```APIDOC ## GET /{-$locale}/about ### Description Matches routes with an optional locale prefix (e.g., /about, /en/about, /fr/about). ### Method GET ### Endpoint /{-$locale}/about ### Parameters #### Path Parameters - **$locale** (string) - Optional - The language code (e.g., en, fr, es). ### Request Example GET /en/about ### Response #### Success Response (200) - **content** (object) - Localized content based on the provided locale parameter. ``` -------------------------------- ### Redirect unauthenticated users from a route Source: https://tanstack.com/router/latest/docs/guide/authenticated-routes.md This code snippet demonstrates how to use the `beforeLoad` function to check for user authentication. If the user is not authenticated, it throws a `redirect` to the login page, passing the current location's href as a search parameter for post-login redirection. It also includes error handling for network issues or token validation failures. ```tsx import { createFileRoute, redirect, isRedirect } from '@tanstack/react-router' // src/routes/_authenticated.tsx export const Route = createFileRoute('/_authenticated')({ beforeLoad: async ({ location }) => { try { const user = await verifySession() // might throw on network error if (!user) { throw redirect({ to: '/login', search: { redirect: location.href }, }) } return { user } } catch (error) { // Re-throw redirects (they're intentional, not errors) if (isRedirect(error)) throw error // Auth check failed (network error, etc.) - redirect to login throw redirect({ to: '/login', search: { redirect: location.href }, }) } }, }) ``` ```tsx import { createFileRoute, redirect, isRedirect } from '@tanstack/solid-router' // src/routes/_authenticated.tsx export const Route = createFileRoute('/_authenticated')({ beforeLoad: async ({ location }) => { try { const user = await verifySession() // might throw on network error if (!user) { throw redirect({ to: '/login', search: { redirect: location.href }, }) } return { user } } catch (error) { // Re-throw redirects (they're intentional, not errors) if (isRedirect(error)) throw error // Auth check failed (network error, etc.) - redirect to login throw redirect({ to: '/login', search: { redirect: location.href }, }) } }, }) ``` -------------------------------- ### Use special relative paths Source: https://tanstack.com/router/latest/docs/guide/navigation.md Using '.' to reload the current route or '..' to navigate to parent routes. ```tsx export const Route = createFileRoute('/posts/$postId')({ component: PostComponent, }) function PostComponent() { return ( <div> <Link to=".">Reload the current route of /posts/$postId</Link> <Link to="..">Navigate back to /posts</Link> // the below are all equivalent <Link to="/posts">Navigate back to /posts</Link> <Link from="/posts" to="."> Navigate back to /posts </Link> // the below are all equivalent <Link to="/">Navigate to root</Link> <Link from="/posts" to=".."> Navigate to root </Link> </div> ) } ``` -------------------------------- ### Default TanStack Router Esbuild Configuration Source: https://tanstack.com/router/latest/docs/installation/with-esbuild.md Review the default configuration options for the TanStack Router Esbuild plugin. These settings cover routes directory, generated file path, ignore prefix, and quote style. ```json { "routesDirectory": "./src/routes", "generatedRouteTree": "./src/routeTree.gen.ts", "routeFileIgnorePrefix": "-", "quoteStyle": "single" } ``` -------------------------------- ### Optional Path Parameters for i18n Routing Source: https://tanstack.com/router/latest/docs/guide/internationalization-i18n.md Demonstrates using optional path parameters to create locale-aware routes without duplicating route definitions. This pattern matches routes with and without a locale prefix, simplifying i18n routing. ```tsx export const Route = createFileRoute('/{-$locale}/about')({ component: AboutComponent, }) function AboutComponent() { const { locale } = Route.useParams() const currentLocale = locale || 'en' const content = { en: { title: 'About Us' }, fr: { title: 'À Propos' }, es: { title: 'Acerca de' }, } return <h1>{content[currentLocale].title}</h1> } ``` -------------------------------- ### Navigate to a New Location (TypeScript) Source: https://tanstack.com/router/latest/docs/api/router/RouterType.md Navigates the application to a new specified location. This function abstracts the underlying history manipulation and routing logic. ```typescript type navigate = (options: NavigateOptions) => Promise<void> ``` -------------------------------- ### Create Login Component with TanStack Router Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md This component handles user login, including email/password input, submission, and error handling. It uses route context for authentication and search parameters for redirection. ```tsx import { createFileRoute, redirect } from '@tanstack/react-router' import { useState } from 'react' export const Route = createFileRoute('/login')({ validateSearch: (search) => ({ redirect: (search.redirect as string) || '/dashboard', }), beforeLoad: ({ context, search }) => { if (context.auth.isAuthenticated) { throw redirect({ to: search.redirect }) } }, component: LoginComponent, }) function LoginComponent() { const { auth } = Route.useRouteContext() const { redirect } = Route.useSearch() const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [isLoading, setIsLoading] = useState(false) const [error, setError] = useState('') const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() setIsLoading(true) setError('') try { await auth.login(email, password) // Supabase auth will automatically update context window.location.href = redirect } catch (err: any) { setError(err.message || 'Login failed') } finally { setIsLoading(false) } } return ( <div className="min-h-screen flex items-center justify-center"> <form onSubmit={handleSubmit} className="max-w-md w-full space-y-4 p-6 border rounded-lg" > <h1 className="text-2xl font-bold text-center">Sign In</h1> {error && ( <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded"> {error} </div> )} <div> <label htmlFor="email" className="block text-sm font-medium mb-1"> Email </label> <input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required /> </div> <div> <label htmlFor="password" className="block text-sm font-medium mb-1"> Password </label> <input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required /> </div> <button type="submit" disabled={isLoading} className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:opacity-50" > {isLoading ? 'Signing in...' : 'Sign In'} </button> </form> </div> ) } ``` -------------------------------- ### Protect Dashboard Route with Authentication (Solid) Source: https://tanstack.com/router/latest/docs/guide/authenticated-routes.md This code snippet defines a route for '/dashboard' using TanStack Router's `createFileRoute`. Before loading the route, it checks if the user is authenticated via `context.auth.isAuthenticated()`. If not authenticated, it throws a `redirect` to the '/login' page, passing the original location as a search parameter. ```tsx import { createFileRoute, redirect } from '@tanstack/solid-router' export const Route = createFileRoute('/dashboard')({ beforeLoad: ({ context, location }) => { if (!context.auth.isAuthenticated()) { throw redirect({ to: '/login', search: { redirect: location.href, }, }) } }, }) ``` -------------------------------- ### Define a Virtual Pathless Route Source: https://tanstack.com/router/latest/docs/routing/virtual-file-routes.md Create a virtual pathless route using the `layout` function, providing a file name and optional children routes. Imports are required. ```typescript // routes.ts import { layout } from '@tanstack/virtual-file-routes' export const routes = rootRoute('root.tsx', [ layout('pathlessLayout.tsx', [ // ... children routes ]), ]) ``` -------------------------------- ### Solid Block Component for UI Blocking Source: https://tanstack.com/router/latest/docs/guide/navigation-blocking.md Illustrates the usage of the `Block` component in SolidJS for implementing UI blocking, similar to the React version. It leverages Solid's reactivity and render props to manage the blocking state and actions. ```tsx import { Block } from '@tanstack/solid-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = createSignal(false) return ( <Block shouldBlockFn={() => formIsDirty()} withResolver> {({ status, proceed, reset }) => ( <> {/* ... */} {status === 'blocked' && ( <div> <p>Are you sure you want to leave?</p> <button onClick={proceed}>Yes</button> <button onClick={reset}>No</button> </div> )} </> )} </Block> ) } ``` -------------------------------- ### Create Clerk Sign-In Route Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Defines the route for user sign-in using Clerk's SignIn component. Ensure the component is wrapped in a layout that provides necessary context. ```tsx import { createFileRoute } from '@tanstack/react-router' import { SignIn } from '@clerk/clerk-react' export const Route = createFileRoute('/sign-in')({ component: () => ( <div className="flex items-center justify-center min-h-screen"> <SignIn redirectUrl="/dashboard" signUpUrl="/sign-up" /> </div> ), }) ``` -------------------------------- ### Configure Default Search Serialization Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md Implements the default JSON-based search parameter serialization and deserialization using TanStack Router's built-in helper functions. ```tsx import { createRouter, parseSearchWith, stringifySearchWith } from '@tanstack/react-router'; const router = createRouter({ parseSearch: parseSearchWith(JSON.parse), stringifySearch: stringifySearchWith(JSON.stringify), }); ``` ```tsx import { createRouter, parseSearchWith, stringifySearchWith } from '@tanstack/solid-router'; const router = createRouter({ parseSearch: parseSearchWith(JSON.parse), stringifySearch: stringifySearchWith(JSON.stringify), }); ``` -------------------------------- ### Multiple Optional Parameters Source: https://tanstack.com/router/latest/docs/guide/navigation.md Handles navigation when multiple optional parameters are defined in the route. ```tsx // Navigate with some optional parameters <Link to="/posts/{-$category}/{-$slug}" params={{ category: 'tech', slug: undefined }} > Tech Posts </Link> // Remove all optional parameters <Link to="/posts/{-$category}/{-$slug}" params={{ category: undefined, slug: undefined }} > All Posts </Link> // Set multiple parameters <Link to="/posts/{-$category}/{-$slug}" params={{ category: 'tech', slug: 'react-tips' }} > Specific Post </Link> ``` -------------------------------- ### Router API Components Source: https://tanstack.com/router/latest/docs/api/router.md Discover the components provided by TanStack Router for rendering UI elements related to routing. ```APIDOC ## Router API Components ### Description Components that integrate with the TanStack Router to manage navigation, display content, and handle routing states. ### Components - **`<Await>`**: Renders children based on the resolution of a promise. - **`<CatchBoundary>`**: Catches errors within a route segment. - **`<CatchNotFound>`**: Catches 'not found' errors within a route segment. - **`<ClientOnly>`**: Renders children only on the client-side. - **`<DefaultGlobalNotFound>`**: A default component for global not found routes. - **`<ErrorComponent>`**: A component to display errors. - **`<Link>`**: Navigates to a different route without a full page reload. - **`<MatchRoute>`**: Conditionally renders content based on route matching. - **`<Navigate>`**: Programmatically navigates to a different route. - **`<NotFoundComponent>`**: A component to display when a route is not found. - **`<Outlet>`**: Renders the matched child route's component. ### Example Usage (Conceptual) ```jsx import { Link, Outlet } from '@tanstack/router' function Layout() { return ( <div> <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> <hr /> <Outlet /> {/* Render matched child route component here */} </div> ) } ``` ``` -------------------------------- ### Combine Prefixes and Suffixes Source: https://tanstack.com/router/latest/docs/guide/path-params.md Wraps a dynamic parameter with both a static prefix and a static suffix. ```tsx export const Route = createFileRoute('/users/user-{$userId}.json')({ component: UserComponent, }) function UserComponent() { const { userId } = Route.useParams() // userId will be the value between 'user-' and '.json' return <div>User ID: {userId}</div> } ``` ```tsx export const Route = createFileRoute('/users/user-{$userId}.json')({ component: UserComponent, }) function UserComponent() { const params = Route.useParams() // userId will be the value between 'user-' and '.json' return <div>User ID: {params().userId}</div> } ``` -------------------------------- ### Define a Virtual Index Route Source: https://tanstack.com/router/latest/docs/routing/virtual-file-routes.md Use the `index` function to create a virtual index route, specifying the file name. Imports are required. ```typescript import { index } from '@tanstack/virtual-file-routes' const routes = rootRoute('root.tsx', [index('index.tsx')]) ``` -------------------------------- ### Optimize LinkProps with as const satisfies Source: https://tanstack.com/router/latest/docs/guide/type-safety.md Use as const satisfies to infer precise types instead of using LinkProps directly, reducing the complexity of type checks. ```tsx const props = { to: '/posts/', } as const satisfies LinkProps return ( <Link {...props}> ) ``` -------------------------------- ### Define a virtual subtree configuration Source: https://tanstack.com/router/latest/docs/routing/virtual-file-routes.md Use defineVirtualSubtreeConfig to specify routes for a directory subtree when using virtual routing. ```typescript // routes/foo/bar/__virtual.ts import { defineVirtualSubtreeConfig, index, route, } from '@tanstack/virtual-file-routes' export default defineVirtualSubtreeConfig([ index('home.tsx'), route('$id', 'details.tsx'), ]) ``` -------------------------------- ### Configure TanStackRouter plugin with inline routes Source: https://tanstack.com/router/latest/docs/routing/virtual-file-routes.md Define the virtual route tree directly within the plugin configuration. ```tsx // vite.config.ts import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' import { rootRoute } from '@tanstack/virtual-file-routes' const routes = rootRoute('root.tsx', [ // ... the rest of your virtual route tree ]) export default defineConfig({ plugins: [tanstackRouter({ virtualRouteConfig: routes }), react()], }) ``` ```tsx // vite.config.ts import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' const routes = rootRoute('root.tsx', [ // ... the rest of your virtual route tree ]) export default defineConfig({ plugins: [ tanstackRouter({ virtualRouteConfig: routes, target: 'react' }), react(), ], }) ``` ```tsx // vite.config.ts import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/vite' const routes = rootRoute('root.tsx', [ // ... the rest of your virtual route tree ]) export default defineConfig({ plugins: [ tanstackRouter({ virtualRouteConfig: routes, target: 'solid' }), solid(), ], }) ``` -------------------------------- ### Navigate with Optional Parameters Source: https://tanstack.com/router/latest/docs/guide/path-params.md Control the inclusion of optional parameters during navigation by setting them to specific values or undefined. ```tsx function Navigation() { return ( <div> {/* Navigate with optional parameter */} <Link to="/posts/{-$category}" params={{ category: 'tech' }}> Tech Posts </Link> {/* Navigate without optional parameter */} <Link to="/posts/{-$category}" params={{ category: undefined }}> All Posts </Link> {/* Navigate with multiple optional parameters */} <Link to="/posts/{-$category}/{-$slug}" params={{ category: 'tech', slug: 'react-tips' }} > Specific Post </Link> </div> ) } ``` -------------------------------- ### TanStackRouterDevtoolsPanel Component Source: https://tanstack.com/router/latest/docs/devtools.md Configuration options for the embedded DevtoolsPanel component. ```APIDOC ## TanStackRouterDevtoolsPanel Options ### Description Configuration properties for the embedded DevtoolsPanel component used in Fixed or Embedded modes. ### Parameters - **router** (Router) - Required - The router instance to connect to. - **style** (StyleObject) - Optional - Inline styles for the component. - **className/class** (string) - Optional - CSS class names for styling. - **isOpen** (boolean) - Optional - Boolean indicating open/closed state. - **setIsOpen** (function) - Optional - Callback to toggle the panel state. - **handleDragStart** (function) - Optional - Handler for drag events. - **shadowDOMTarget** (ShadowRoot) - Optional - Specifies a Shadow DOM target for styles. ``` -------------------------------- ### Use Optional Parameters in Loaders Source: https://tanstack.com/router/latest/docs/guide/path-params.md Loaders receive optional parameters which may be undefined. ```tsx export const Route = createFileRoute('/posts/{-$category}')({ loader: async ({ params }) => { // params.category might be undefined return fetchPosts({ category: params.category }) }, }) ``` -------------------------------- ### Define a Virtual Route Source: https://tanstack.com/router/latest/docs/routing/virtual-file-routes.md Use the `route` function to create a virtual route with a path, file name, and optional children. Imports are required. ```typescript import { route } from '@tanstack/virtual-file-routes' export const routes = rootRoute('root.tsx', [ route('/about', 'about.tsx', [ // ... children routes ]), ]) ``` -------------------------------- ### Define Layout Routes Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md Create a layout by nesting child routes under a parent route that defines a component. ```tsx const postsRoute = createRoute({ getParentRoute: () => rootRoute, path: 'posts', component: PostsLayoutComponent, // The layout component }) function PostsLayoutComponent() { return ( <div> <h1>Posts</h1> <Outlet /> </div> ) } const postsIndexRoute = createRoute({ getParentRoute: () => postsRoute, path: '/', }) const postsCreateRoute = createRoute({ getParentRoute: () => postsRoute, path: 'create', }) const routeTree = rootRoute.addChildren([ // The postsRoute is the layout route // Its children will be nested under the PostsLayoutComponent postsRoute.addChildren([postsIndexRoute, postsCreateRoute]), ]) ``` ```tsx // URL: /posts <PostsLayoutComponent> <PostsIndexComponent /> </PostsLayoutComponent> // URL: /posts/create <PostsLayoutComponent> <PostsCreateComponent /> </PostsLayoutComponent> ``` -------------------------------- ### retainSearchParams Middleware Configuration Source: https://tanstack.com/router/latest/docs/api/router/retainSearchParamsFunction.md Demonstrates how to configure the retainSearchParams middleware within the root route to retain specific search parameters. ```APIDOC ## retainSearchParams Middleware ### Description The `retainSearchParams` middleware is used to automatically retain search parameters during navigation. It can be configured to retain all search parameters or a specific list of keys. ### Method Configuration within `createRootRoute` or `createFileRoute`'s `search.middlewares` property. ### Endpoint N/A (Middleware configuration) ### Parameters - **retainSearchParams** (boolean | string[]) - Required - Accepts `true` to retain all search params, or an array of strings representing the keys of search params to retain. ### Request Example ```tsx import { z } from 'zod' import { createRootRoute, retainSearchParams } from '@tanstack/react-router' const searchSchema = z.object({ rootValue: z.string().optional(), otherValue: z.string().optional() }) export const Route = createRootRoute({ validateSearch: searchSchema, search: { middlewares: [ retainSearchParams(['rootValue']) // Retains only 'rootValue' ], }, }) ``` ### Response N/A (Middleware configuration) #### Response Example N/A ``` -------------------------------- ### Render Application on Server with defaultRenderHandler Source: https://tanstack.com/router/latest/docs/guide/ssr.md Uses the default render handler to process server-side requests. ```tsx import { createRequestHandler, defaultRenderHandler, } from '@tanstack/react-router/ssr/server' import { createRouter } from './router' export async function render({ request }: { request: Request }) { const handler = createRequestHandler({ request, createRouter }) return await handler(defaultRenderHandler) } ``` ```tsx import { createRequestHandler, defaultRenderHandler, } from '@tanstack/solid-router/ssr/server' import { createRouter } from './router' export async function render({ request }: { request: Request }) { const handler = createRequestHandler({ request, createRouter }) return await handler(defaultRenderHandler) } ``` -------------------------------- ### Configure external cache integration Source: https://tanstack.com/router/latest/docs/guide/data-loading.md Set defaultPreloadStaleTime to 0 to ensure all load events trigger loader functions for external cache handling. ```tsx const router = createRouter({ routeTree, defaultPreloadStaleTime: 0, }) ``` -------------------------------- ### Dynamic Post Route with Data Fetching (React) Source: https://tanstack.com/router/latest/docs/guide/deferred-data-loading.md This React code defines a dynamic route for individual posts using TanStack Router. It utilizes `useSuspenseQuery` from `@tanstack/react-query` to fetch data asynchronously. The component handles loading states with Suspense and displays deferred data. ```tsx import { createFileRoute } from '@tanstack/react-router' import { useSuspenseQuery } from '@tanstack/react-query' import { slowDataOptions, fastDataOptions } from '~/api/query-options' export const Route = createFileRoute('/posts/$postId')({ // ... component: PostIdComponent, }) function PostIdComponent() { const fastData = useSuspenseQuery(fastDataOptions()) // do something with fastData return ( <Suspense fallback={<div>Loading...</div>}> <SlowDataComponent /> </Suspense> ) } function SlowDataComponent() { const data = useSuspenseQuery(slowDataOptions()) return <div>{data}</div> } ``` -------------------------------- ### Define Optional Parameters with Prefix and Suffix Source: https://tanstack.com/router/latest/docs/guide/path-params.md Optional parameters can be embedded within static path segments. ```tsx // Route: /files/prefix{-$name}.txt // Matches: /files/prefix.txt and /files/prefixdocument.txt export const Route = createFileRoute('/files/prefix{-$name}.txt')({ component: FileComponent, }) function FileComponent() { const { name } = Route.useParams() return <div>File: {name || 'default'}</div> } ``` ```tsx // Route: /files/prefix{-$name}.txt // Matches: /files/prefix.txt and /files/prefixdocument.txt export const Route = createFileRoute('/files/prefix{-$name}.txt')({ component: FileComponent, }) function FileComponent() { const params = Route.useParams() return <div>File: {params().name || 'default'}</div> } ``` -------------------------------- ### Prerender Localized Routes Source: https://tanstack.com/router/latest/docs/guide/internationalization-i18n.md Maps application paths to their localized versions using the localizeHref utility. This is essential for static site generation where localized routes need to be explicitly defined for the prerenderer. ```typescript import { localizeHref } from './paraglide/runtime' export const prerenderRoutes = ['/', '/about'].map((path) => ({ path: localizeHref(path), prerender: { enabled: true }, })) ``` -------------------------------- ### Watch for Route Changes with CLI Source: https://tanstack.com/router/latest/docs/installation/with-router-cli.md Execute the 'tsr watch' command to continuously monitor directories and automatically regenerate routes when files change. ```bash tsr watch ``` -------------------------------- ### Register Router for Solid Type Safety Source: https://tanstack.com/router/latest/docs/guide/type-safety.md Register your router with the `@tanstack/solid-router` module using declaration merging on the `Register` interface. This enables top-level exports to correctly infer types from your router. ```ts const router = createRouter({ // ... }) declare module '@tanstack/solid-router' { interface Register { router: typeof router } } ``` -------------------------------- ### Protect Route with beforeLoad Hook Source: https://tanstack.com/router/latest/docs/how-to/setup-authentication.md Use the `beforeLoad` function in route configuration to check authentication status from context and throw a redirect if the user is not authenticated. This prevents flashing protected content before redirection. ```tsx export const Route = createFileRoute('/_authenticated/dashboard')({ beforeLoad: ({ context }) => { if (!context.auth.isAuthenticated) { throw redirect({ to: '/login' }) } }, component: DashboardComponent, }) ``` -------------------------------- ### Building a New Location Source: https://tanstack.com/router/latest/docs/api/router/RouterType.md Illustrates the use of .buildLocation to generate a ParsedLocation object. This is useful for preparing navigation paths with dynamic parameters or search states. ```typescript const nextLocation = router.buildLocation({ to: '/users/$userId', params: { userId: '456' }, search: { tab: 'settings' } }); ``` -------------------------------- ### Link Component Children as a Function Source: https://tanstack.com/router/latest/docs/guide/navigation.md Demonstrates how to use a function as a child of the Link component to access and utilize the `isActive` state for conditional styling or rendering. ```APIDOC ## Link Component Children as a Function ### Description The `Link` component accepts a function for its children. This function receives an `isActive` boolean, allowing you to propagate the link's active state to child elements for conditional styling or behavior. ### Example ```tsx const link = ( <Link to="/blog/post"> {({ isActive }) => { return ( <> <span>My Blog Post</span> <icon className={isActive ? 'active' : 'inactive'} /> </> ) }} </Link> ) ``` ``` -------------------------------- ### Mixed Required and Optional Parameters Source: https://tanstack.com/router/latest/docs/guide/navigation.md Combines required path parameters with optional ones. ```tsx // Required 'id', optional 'tab' <Link to="/users/$id/{-$tab}" params={{ id: '123', tab: 'settings' }} > User Settings </Link> // Remove optional parameter while keeping required <Link to="/users/$id/{-$tab}" params={{ id: '123', tab: undefined }} > User Profile </Link> // Use function style with mixed parameters <Link to="/users/$id/{-$tab}" params={(prev) => ({ ...prev, tab: 'notifications' })} > User Notifications </Link> ``` -------------------------------- ### Configure Default Router-Wide Not Found Handling Source: https://tanstack.com/router/latest/docs/guide/not-found-errors.md Provide a `defaultNotFoundComponent` to the `createRouter` function for a fallback not-found handler across all routes with child routes. Leaf-node routes cannot handle not-found errors. ```tsx const router = createRouter({ defaultNotFoundComponent: () => { return ( <div> <p>Not found!</p> <Link to="/">Go home</Link> </div> ) }, }) ``` -------------------------------- ### Define Optional Path Parameters Source: https://tanstack.com/router/latest/docs/guide/path-params.md Use curly braces with a dash prefix to define optional segments in route paths. ```tsx // Single optional parameter // src/routes/posts/{-$category}.tsx export const Route = createFileRoute('/posts/{-$category}')({ component: PostsComponent, }) // Multiple optional parameters // src/routes/posts/{-$category}/{-$slug}.tsx export const Route = createFileRoute('/posts/{-$category}/{-$slug}')({ component: PostComponent, }) // Mixed required and optional parameters // src/routes/users/$id/{-$tab}.tsx export const Route = createFileRoute('/users/$id/{-$tab}')({ component: UserComponent, }) ``` -------------------------------- ### Use Type-Safe Route References Source: https://tanstack.com/router/latest/docs/guide/navigation.md Utilize the `to` property of a route object to enable type-safe navigation instead of using plain strings. ```tsx import { Route as aboutRoute } from './routes/about.tsx' function Comp() { return <Link to={aboutRoute.to}>About</Link> } ``` -------------------------------- ### Declarative Route Masking with Router Option Source: https://tanstack.com/router/latest/docs/guide/route-masking.md Illustrates how to declaratively define route masks using the `routeMasks` option when creating a router in TanStack Router. This approach allows for global route masking rules to be applied. ```tsx import { createRouteMask } from '@tanstack/react-router' const photoModalToPhotoMask = createRouteMask({ routeTree, from: '/photos/$photoId/modal', to: '/photos/$photoId', params: (prev) => ({ photoId: prev.photoId, }), }) const router = createRouter({ routeTree, routeMasks: [photoModalToPhotoMask], }) ``` -------------------------------- ### Use Optional Parameters in beforeLoad Source: https://tanstack.com/router/latest/docs/guide/path-params.md beforeLoad handlers can validate optional parameters if they are present. ```tsx export const Route = createFileRoute('/posts/{-$category}')({ beforeLoad: async ({ params }) => { if (params.category) { // Validate category exists await validateCategory(params.category) } }, }) ``` -------------------------------- ### Define Router Context Source: https://tanstack.com/router/latest/docs/guide/type-safety.md Use createRootRouteWithContext to enforce a type contract for context across the route tree. ```tsx const rootRoute = createRootRouteWithContext<{ whateverYouWant: true }>()({ component: App, }) const routeTree = rootRoute.addChildren([ // ... all child routes will have access to `whateverYouWant` in their context ]) const router = createRouter({ routeTree, context: { // This will be required to be passed now whateverYouWant: true, }, }) ``` -------------------------------- ### MatchRouteOptions Type Source: https://tanstack.com/router/latest/docs/api/router/MatchRouteOptionsType.md Defines the options available for matching routes in TanStack Router. ```APIDOC ## MatchRouteOptions Type ### Description The `MatchRouteOptions` type is used to describe the options that can be used when matching a route. ### Properties - **pending** (boolean) - Optional - If `true`, will match against pending location instead of the current location. - **includeSearch** (boolean) - Optional - If `true`, will match against the current location's search params using a deep inclusive check. e.g. `{ a: 1 }` will match for a current location of `{ a: 1, b: 2 }`. - **fuzzy** (boolean) - Optional - If `true`, will match against the current location using a fuzzy match. e.g. `/posts` will match for a current location of `/posts/123`. ### Deprecated Properties - **~~caseSensitive~~** (boolean) - Optional - If `true`, will match against the current location with case sensitivity. Declare case sensitivity in the route definition instead, or globally for all routes using the `caseSensitive` option on the router. ``` -------------------------------- ### NotFoundComponent API Reference Source: https://tanstack.com/router/latest/docs/api/router/notFoundComponentComponent.md Details on the props and usage of the NotFoundComponent in TanStack Router. ```APIDOC ## NotFoundComponent ### Description The `NotFoundComponent` is a UI component that renders when a route is not found. It provides context about the error to allow for customized 404 page rendering. ### Props - **data** (unknown) - Optional - Custom data passed to the component from the `NotFoundError` object. - **isNotFound** (boolean) - Required - Indicates the current state is a not-found error (always true). - **routeId** (RouteIds) - Required - The ID of the route attempting to handle the error. ### Usage Example ```tsx <NotFoundComponent isNotFound={true} routeId="/posts/$postId" data={{ message: "Post not found" }} /> ``` ### Returns - Returns a React component representing the UI for the not-found error state. ``` -------------------------------- ### redirect Function for Type-Safe Redirects Source: https://tanstack.com/router/latest/docs/api/router/RouteApiType.md A type-safe utility for creating redirect objects, intended for use in `beforeLoad` or `loader` callbacks. It automatically sets the `from` parameter to the current route ID, enabling relative pathing and type-safe redirects. It accepts options from the base `redirect` function. ```typescript redirect(opts?: RedirectOptions): Redirect ``` ```typescript import { getRouteApi } from '@tanstack/react-router' const routeApi = getRouteApi('/dashboard/settings') export const Route = createFileRoute('/dashboard/settings')({ beforeLoad: ({ context }) => { if (!context.user) { // Type-safe redirect - 'from' is automatically '/dashboard/settings' throw routeApi.redirect({ to: '../login', // Relative path to sibling route }) } }, }) ``` -------------------------------- ### Implement Streaming SSR with defaultStreamHandler Source: https://tanstack.com/router/latest/docs/guide/ssr.md Use defaultStreamHandler to automatically stream markup and data to the client. ```tsx import { createRequestHandler, defaultStreamHandler, } from '@tanstack/react-router/ssr/server' import { createRouter } from './router' export async function render({ request }: { request: Request }) { const handler = createRequestHandler({ request, createRouter }) return await handler(defaultStreamHandler) } ``` ```tsx import { createRequestHandler, defaultStreamHandler, } from '@tanstack/solid-router/ssr/server' import { createRouter } from './router' export async function render({ request }: { request: Request }) { const handler = createRequestHandler({ request, createRouter }) return await handler(defaultStreamHandler) } ``` -------------------------------- ### Validating and Using Search Params in Solid Loaders Source: https://tanstack.com/router/latest/docs/guide/data-loading.md Utilize `validateSearch` to parse and validate search parameters, and `loaderDeps` to pass specific validated parameters to your loader function. This ensures data fetching is based on unique URL states and prevents caching bugs. ```tsx // /routes/users.user.tsx export const Route = createFileRoute('/users/user')({ validateSearch: (search) => search as { userId: string }, loaderDeps: ({ search: { userId } }) => ({ userId, }), loader: async ({ deps: { userId } }) => getUser(userId), }) ``` ```tsx // /routes/posts.tsx export const Route = createFileRoute('/posts')({ // Use zod to validate and parse the search params validateSearch: z.object({ offset: z.number().int().nonnegative().catch(0), }), // Pass the offset to your loader deps via the loaderDeps function loaderDeps: ({ search: { offset } }) => ({ offset }), // Use the offset from context in the loader function loader: async ({ deps: { offset } }) => fetchPosts({ offset, }), }) ``` -------------------------------- ### LinkOptions Type Definition Source: https://tanstack.com/router/latest/docs/api/router/LinkOptionsType.md Defines the configuration object used for link navigation and anchor element attributes. ```APIDOC ## LinkOptions Type ### Description The LinkOptions type extends NavigateOptions and provides additional configuration for rendering and behavior of anchor elements within TanStack Router. ### Properties - **target** (HTMLAnchorElement['target']) - Optional - The standard anchor tag target attribute. - **activeOptions** (ActiveOptions) - Optional - Options used to determine if the link is currently active. - **preload** (false | 'intent' | 'viewport' | 'render') - Optional - Defines the preloading strategy for the link. - **preloadDelay** (number) - Optional - Delay in milliseconds before triggering intent-based preloading. - **disabled** (boolean) - Optional - If true, renders the link without an href attribute. ### Usage Example ```tsx <Link to="/profile" target="_blank" preload="intent" preloadDelay={200} /> ``` ``` -------------------------------- ### Admin Dashboard Page Source: https://tanstack.com/router/latest/docs/how-to/setup-rbac.md A sample admin dashboard component that displays user information and links to different admin sections. It uses route context to access user details. ```typescript import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/_authenticated/_admin/dashboard')({ component: AdminDashboard, }) function AdminDashboard() { const { auth } = Route.useRouteContext() return ( <div className="p-6"> <h1 className="text-3xl font-bold mb-6">Admin Dashboard</h1> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"> <div className="bg-white p-6 rounded-lg shadow"> <h2 className="text-xl font-semibold mb-2">User Management</h2> <p className="text-gray-600">Manage all users in the system</p> <button className="mt-4 bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"> View Users </button> </div> <div className="bg-white p-6 rounded-lg shadow"> <h2 className="text-xl font-semibold mb-2">System Settings</h2> <p className="text-gray-600">Configure system-wide settings</p> <button className="mt-4 bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700"> Open Settings </button> </div> <div className="bg-white p-6 rounded-lg shadow"> <h2 className="text-xl font-semibold mb-2">Reports</h2> <p className="text-gray-600">View system reports and analytics</p> <button className="mt-4 bg-purple-600 text-white px-4 py-2 rounded hover:bg-purple-700"> View Reports </button> </div> </div> <div className="mt-8 bg-gray-100 p-4 rounded"> <h3 className="font-semibold">Your Info:</h3> <p>Username: {auth.user?.username}</p> <p>Roles: {auth.user?.roles.join(', ')}</p> <p>Permissions: {auth.user?.permissions.join(', ')}</p> </div> </div> ) } ``` -------------------------------- ### Create Advanced MUI Link with Custom Props Source: https://tanstack.com/router/latest/docs/guide/custom-link.md Wraps an MUI Link component using React.forwardRef and custom props. This approach allows for additional configuration like preloading behavior. ```tsx import React from 'react' import { createLink } from '@tanstack/react-router' import { Link } from '@mui/material' import type { LinkProps } from '@mui/material' import type { LinkComponent } from '@tanstack/react-router' interface MUILinkProps extends LinkProps {} const MUILinkComponent = React.forwardRef<HTMLAnchorElement, MUILinkProps>( (props, ref) => <Link ref={ref} {...props} />, ) const CreatedLinkComponent = createLink(MUILinkComponent) export const CustomLink: LinkComponent<typeof MUILinkComponent> = (props) => { return <CreatedLinkComponent preload={'intent'} {...props} /> } ``` -------------------------------- ### Type Definition: UseMatchRouteOptions Source: https://tanstack.com/router/latest/docs/api/router/UseMatchRouteOptionsType.md Explains the structure and composition of the UseMatchRouteOptions type. ```APIDOC ## UseMatchRouteOptions Type ### Description The `UseMatchRouteOptions` type is used to configure the behavior of the `useMatchRoute` hook. It inherits properties from `ToOptions` for navigation path resolution and `MatchRouteOptions` for fine-grained matching logic. ### Definition ```typescript export type UseMatchRouteOptions = ToOptions & MatchRouteOptions ``` ### Inherited Types - **ToOptions**: Provides options for defining the target route, including path, params, and search parameters. - **MatchRouteOptions**: Provides options for matching behavior, such as strict matching, fuzzy matching, and case sensitivity. ### Usage This type is passed as the second argument to the `useMatchRoute` hook to determine if the current route matches the specified criteria. ``` -------------------------------- ### Create Protected Route with Auth0 Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Define a protected route that redirects to login if the user is not authenticated. This uses the `beforeLoad` hook in TanStack Router. ```tsx import { createFileRoute, redirect, Outlet } from '@tanstack/react-router' export const Route = createFileRoute('/_authenticated')({ beforeLoad: ({ context, location }) => { if (!context.auth.isAuthenticated) { // Auth0 handles login redirects, so just trigger login context.auth.login() return } }, component: () => <Outlet />, }) ``` -------------------------------- ### Configure Vite Plugin for TanStack Router Source: https://tanstack.com/router/latest/docs/installation/manual.md Configure the Vite plugin for TanStack Router, ensuring it's placed before the React plugin. Supports auto code splitting. ```typescript import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ // Please make sure that '@tanstack/router-plugin' is passed before '@vitejs/plugin-react' tanstackRouter({ target: 'react', autoCodeSplitting: true, }), react(), // ..., ], }) ``` -------------------------------- ### Access Path Params in Component (Solid) Source: https://tanstack.com/router/latest/docs/guide/path-params.md Demonstrates accessing path parameters in a Solid component using `Route.useParams()`. The `postId` is accessed from the returned object. ```tsx export const Route = createFileRoute('/posts/$postId')({ component: PostComponent, }) function PostComponent() { const params = Route.useParams() return <div>Post {params().postId}</div> } ``` -------------------------------- ### HeadContent Component Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md The `<HeadContent />` component is required to render head, title, meta, link, and head-related script tags. ```APIDOC ## HeadContent Component ### Description The `<HeadContent />` component is required to render the head, title, meta, link, and head-related script tags of a document. It should be rendered either in the `<head>` tag of your root layout or as high up in the component tree as possible. ### Method N/A (Component) ### Endpoint N/A (Component) ### Parameters #### Props - **assetCrossOrigin** (string | object) - Optional - Applies to manifest-managed asset links emitted by Start. Can be a string like 'anonymous' or an object like `{ modulepreload: 'anonymous', stylesheet: 'use-credentials' }`. ### Request Example ```tsx // In root layout's <head> tag <HeadContent /> // Or high up in the component tree <HeadContent assetCrossOrigin="anonymous" /> <HeadContent assetCrossOrigin={{ modulepreload: 'anonymous', stylesheet: 'use-credentials', }} /> ``` ### Response N/A (Component) ``` -------------------------------- ### Define route tree with object syntax Source: https://tanstack.com/router/latest/docs/guide/type-safety.md Use object syntax with addChildren for better TypeScript performance in large route trees compared to tuples. ```tsx const routeTree = rootRoute.addChildren({ postsRoute: postsRoute.addChildren({ postRoute, postsIndexRoute }), indexRoute, }) ``` -------------------------------- ### Define Pathless Layout Routes Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md Use an 'id' instead of a 'path' to create a layout route that does not contribute to the URL structure. ```tsx const pathlessLayoutRoute = createRoute({ getParentRoute: () => rootRoute, id: 'pathlessLayout', component: PathlessLayoutComponent, }) function PathlessLayoutComponent() { return ( <div> <h1>Pathless Layout</h1> <Outlet /> </div> ) } const pathlessLayoutARoute = createRoute({ getParentRoute: () => pathlessLayoutRoute, path: 'route-a', }) const pathlessLayoutBRoute = createRoute({ getParentRoute: () => pathlessLayoutRoute, path: 'route-b', }) const routeTree = rootRoute.addChildren([ // The pathless layout route has no path, only an id // So its children will be nested under the pathless layout route pathlessLayoutRoute.addChildren([pathlessLayoutARoute, pathlessLayoutBRoute]), ]) ``` ```tsx // URL: /route-a <PathlessLayoutComponent> <RouteAComponent /> </PathlessLayoutComponent> // URL: /route-b <PathlessLayoutComponent> <RouteBComponent /> </PathlessLayoutComponent> ``` -------------------------------- ### Define Post Route with Path Param (React) Source: https://tanstack.com/router/latest/docs/guide/path-params.md Defines a route for individual posts using a '$postId' path parameter. The loader function fetches post data using the extracted `postId`. ```tsx import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params }) => { return fetchPost(params.postId) }, }) ``` -------------------------------- ### Integrating Devtools in Root Route Source: https://tanstack.com/router/latest/docs/devtools.md Render the devtools component within your root route component to automatically connect it to the router instance. ```tsx import { createRootRoute, Outlet } from '@tanstack/react-router'; import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'; export const Route = createRootRoute({ component: () => ( <> <Outlet /> <TanStackRouterDevtools /> </> ), }); ``` ```tsx import { createRootRoute, Outlet } from '@tanstack/solid-router'; import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools'; export const Route = createRootRoute({ component: () => ( <> <Outlet /> <TanStackRouterDevtools /> </> ), }); ``` -------------------------------- ### Configure Rspack for React Source: https://tanstack.com/router/latest/docs/installation/with-rspack.md Add the TanStack Router plugin to your rsbuild.config.ts for React projects. ```ts import { defineConfig } from '@rsbuild/core' import { pluginReact } from '@rsbuild/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/rspack' export default defineConfig({ plugins: [pluginReact()], tools: { rspack: { plugins: [ tanstackRouter({ target: 'react', autoCodeSplitting: true, }), ], }, }, }) ``` -------------------------------- ### Create Post Route with Static Title - Solid.js Source: https://tanstack.com/router/latest/docs/guide/static-route-data.md Defines a route for individual posts using a dynamic route parameter '$postId'. It includes static data to set the page title for SEO and navigation purposes. This is useful for setting metadata that is known at route creation time. ```tsx import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/posts/$postId')({ staticData: { getTitle: () => 'Post Details', }, }) ``` -------------------------------- ### Generate Link Options with TypeScript Source: https://tanstack.com/router/latest/docs/api/router/linkOptions.md The linkOptions function is used to create type-checked link configurations for TanStack Router. It accepts an object literal with route properties like 'to' and 'search', and returns an object that can be spread onto routing components such as Link. ```tsx const userLinkOptions = linkOptions({ to: '/dashboard/users/user', search: { usersView: { sortBy: 'email', filterBy: 'filter', }, userId: 0, }, }) function DashboardComponent() { return <Link {...userLinkOptions} /> } ``` -------------------------------- ### Imperative Route Masking with navigate() API Source: https://tanstack.com/router/latest/docs/guide/route-masking.md Shows how to implement imperative route masking using the `navigate()` function provided by TanStack Router's `useNavigate` hook. The `mask` option is used to define the URL that will be persisted in the browser's history. ```tsx const navigate = useNavigate() function onOpenPhoto() { navigate({ to: '/photos/$photoId/modal', params: { photoId: 5 }, mask: { to: '/photos/$photoId', params: { photoId: 5, }, }, }) } ``` -------------------------------- ### Integrate React Aria Components with createLink Source: https://tanstack.com/router/latest/docs/guide/custom-link.md Shows how to wrap React Aria components like Link and MenuItem to enable TanStack Router's navigation features while preserving render props. ```tsx import { createLink } from '@tanstack/react-router' import { Link as RACLink, MenuItem } from 'react-aria-components' export const Link = createLink(RACLink) export const MenuItemLink = createLink(MenuItem) ``` ```tsx import { createLink } from '@tanstack/react-router' import { Link as RACLink, type LinkProps } from 'react-aria-components' interface MyLinkProps extends LinkProps {} function MyLink(props: MyLinkProps) { return ( <RACLink {...props} style={({ isHovered }) => ({ color: isHovered ? 'red' : 'blue' })} /> ) } export const Link = createLink(MyLink) ``` -------------------------------- ### Create a virtual root route Source: https://tanstack.com/router/latest/docs/routing/virtual-file-routes.md The rootRoute function initializes the virtual route tree with a root file and child routes. ```tsx // routes.ts import { rootRoute } from '@tanstack/virtual-file-routes' export const routes = rootRoute('root.tsx', [ // ... children routes ]) ``` -------------------------------- ### ToOptions Interface Source: https://tanstack.com/router/latest/docs/guide/navigation.md The core interface used for all navigation and route matching operations in TanStack Router. ```APIDOC ## ToOptions Interface ### Description The `ToOptions` interface defines the structure for navigation and route matching. It supports relative navigation by defining an origin (`from`) and a destination (`to`), along with parameters, search queries, and state management. ### Parameters - **from** (string) - Optional - The origin route path or ID. If omitted, the router assumes the root path. - **to** (string) - Required - The destination route path (absolute or relative). - **params** (Record<string, unknown> | function) - Required - Path parameters to interpolate into the URL. - **search** (Record<string, unknown> | function) - Required - Query parameters for the URL. - **hash** (string | function) - Optional - URL hash fragment. - **state** (Record<string, any> | function) - Optional - History state for passing data between routes. - **mask** (ToMaskOptions) - Optional - Configuration for masking the URL in the browser. ### Request Example { "from": "/posts", "to": "/posts/$postId", "params": { "postId": "123" }, "search": { "view": "edit" } } ``` -------------------------------- ### createRouter Function API Source: https://tanstack.com/router/latest/docs/api/router/createRouterFunction.md Details about the createRouter function, its options, and what it returns. ```APIDOC ## createRouter Function ### Description The `createRouter` function accepts a [`RouterOptions`](./RouterOptionsType.md) object and creates a new [`Router`](./RouterClass.md) instance. ### Parameters #### Request Body - **options** (RouterOptions) - Required - The options that will be used to configure the router instance. ### Returns - **Router** - An instance of the [`Router`](./RouterType.md). ### Examples ```tsx import { createRouter, RouterProvider } from '@tanstack/react-router' import { routeTree } from './routeTree.gen' const router = createRouter({ routeTree, defaultPreload: 'intent', }) export default function App() { return <RouterProvider router={router} /> } ``` ``` -------------------------------- ### Define Multiple Optional Parameters Source: https://tanstack.com/router/latest/docs/routing/routing-concepts.md Multiple optional parameters can be defined in a single route path. ```tsx // The `-$category` segment is optional, so this route matches both `/posts` and `/posts/tech` import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/posts/{-$category}/{-$slug}')({ component: PostsComponent, }) ``` ```tsx // The `-$category` segment is optional, so this route matches both `/posts` and `/posts/tech` import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/posts/{-$category}/{-$slug}')({ component: PostsComponent, }) ``` -------------------------------- ### Matching Route with MatchRoute Component (Conditional Rendering) Source: https://tanstack.com/router/latest/docs/guide/navigation.md The `<MatchRoute>` component can render children directly when a route is matched. Use the `pending` prop to show UI during route transitions. ```tsx function Component() { return ( <div> <Link to="/users"> Users <MatchRoute to="/users" pending> <Spinner /> </MatchRoute> </Link> </div> ) } ``` -------------------------------- ### Extend Authentication Context with Roles and Permissions Source: https://tanstack.com/router/latest/docs/how-to/setup-rbac.md Update your authentication context to include user roles and permissions. This involves defining a User interface and providing methods to check for roles and permissions within the AuthProvider. ```tsx import React, { createContext, useContext, useState } from 'react' interface User { id: string username: string email: string roles: string[] permissions: string[] } interface AuthState { isAuthenticated: boolean user: User | null hasRole: (role: string) => boolean hasAnyRole: (roles: string[]) => boolean hasPermission: (permission: string) => boolean hasAnyPermission: (permissions: string[]) => boolean login: (username: string, password: string) => Promise<void> logout: () => void } const AuthContext = createContext<AuthState | undefined>(undefined) export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState<User | null>(null) const [isAuthenticated, setIsAuthenticated] = useState(false) const hasRole = (role: string) => { return user?.roles.includes(role) ?? false } const hasAnyRole = (roles: string[]) => { return roles.some((role) => user?.roles.includes(role)) ?? false } const hasPermission = (permission: string) => { return user?.permissions.includes(permission) ?? false } const hasAnyPermission = (permissions: string[]) => { return ( permissions.some((permission) => user?.permissions.includes(permission), ) ?? false ) } const login = async (username: string, password: string) => { const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }), }) if (response.ok) { const userData = await response.json() setUser(userData) setIsAuthenticated(true) } else { throw new Error('Authentication failed') } } const logout = () => { setUser(null) setIsAuthenticated(false) } return ( <AuthContext.Provider value={{ isAuthenticated, user, hasRole, hasAnyRole, hasPermission, hasAnyPermission, login, logout, }} > {children} </AuthContext.Provider> ) } export function useAuth() { const context = useContext(AuthContext) if (context === undefined) { throw new Error('useAuth must be used within an AuthProvider') } return context } ``` -------------------------------- ### Access Path Params Outside Routes (Solid) Source: https://tanstack.com/router/latest/docs/guide/path-params.md Demonstrates accessing path parameters from any component in Solid using `useParams({ strict: false })`. The params are accessed from the returned object. ```tsx function PostComponent() { const params = useParams({ strict: false }) return <div>Post {params().postId}</div> } ``` -------------------------------- ### Error Handling with TanStack Query and Suspense (React) Source: https://tanstack.com/router/latest/docs/guide/external-data-loading.md Demonstrates error handling for data fetching with TanStack Query and suspense in TanStack Router. It uses `useQueryErrorResetBoundary` to reset query errors on component mount and provides a retry mechanism by invalidating the router on button click. ```tsx export const Route = createFileRoute('/')({ loader: () => queryClient.ensureQueryData(postsQueryOptions), errorComponent: ({ error, reset }) => { const router = useRouter() const queryErrorResetBoundary = useQueryErrorResetBoundary() useEffect(() => { // Reset the query error boundary queryErrorResetBoundary.reset() }, [queryErrorResetBoundary]) return ( <div> {error.message} <button onClick={() => { // Invalidate the route to reload the loader, and reset any router error boundaries router.invalidate() }}> retry </button> </div> ) }, }) ``` -------------------------------- ### Debug User Data Loading Source: https://tanstack.com/router/latest/docs/how-to/setup-rbac.md Ensure authentication API responses include necessary roles and permissions for authorization checks. ```tsx const login = async (username: string, password: string) => { const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }), }) if (response.ok) { const userData = await response.json() // Ensure userData includes roles and permissions console.log('User data:', userData) // Debug log setUser(userData) setIsAuthenticated(true) } } ``` -------------------------------- ### RouteMask Configuration Source: https://tanstack.com/router/latest/docs/api/router/RouteMaskType.md Defines the structure and properties required to implement a RouteMask in TanStack Router. ```APIDOC ## RouteMask Type Definition ### Description The `RouteMask` type is used to configure how a route is masked within the application. It extends `ToOptions` to provide full routing capabilities while adding specific mask-related configuration. ### Properties - **...ToOptions** (ToOptions) - Required - The base routing options used to configure the mask. - **routeTree** (TRouteTree) - Required - The route tree structure that the mask will support. - **unmaskOnReload** (boolean) - Optional - If set to true, the mask is cleared when the browser page is reloaded. ### Usage Example ```typescript const myMask: RouteMask = { to: '/dashboard', routeTree: myRouteTree, unmaskOnReload: true }; ``` ``` -------------------------------- ### SolidJS Router Configuration with Zipson Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md Configures the TanStack Router for SolidJS, utilizing zipson for custom search parameter serialization and deserialization. It employs binary encoding and decoding to handle non-UTF8 characters safely in search parameters. ```tsx import { Router, parseSearchWith, stringifySearchWith, } from '@tanstack/solid-router' import { stringify, parse } from 'zipson' const router = createRouter({ parseSearch: parseSearchWith((value) => parse(decodeFromBinary(value))), stringifySearch: stringifySearchWith((value) => encodeToBinary(stringify(value)), ), }) function decodeFromBinary(str: string): string { return decodeURIComponent( Array.prototype.map .call(atob(str), function (c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2) }) .join(''), ) } function encodeToBinary(str: string): string { return btoa( encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) { return String.fromCharCode(parseInt(p1, 16)) }), ) } ``` -------------------------------- ### Solid Menu Component Source: https://tanstack.com/router/latest/docs/guide/type-utilities.md A Solid.js component for rendering a navigation menu. It uses Solid's For component for efficient rendering of items. ```tsx import { For } from 'solid-js' export interface MenuProps< TRouter extends RegisteredRouter = RegisteredRouter, TItems extends ReadonlyArray<unknown> = ReadonlyArray<unknown>, TFrom extends string = string, > { from: ValidateFromPath<TRouter, TFrom> items: ValidateLinkOptionsArray<TRouter, TItems, TFrom> } export function Menu< TRouter extends RegisteredRouter = RegisteredRouter, TItems extends ReadonlyArray<unknown>, TFrom extends string = string, >(props: MenuProps<TRouter, TItems, TFrom>): Solid.JSX.Element export function Menu(props: MenuProps): Solid.JSX.Element { return ( <ul> <For each={props.items}> {(item) => ( <li> <Link {...item} from={props.from} /> </li> )} </For> </ul> ) } ``` -------------------------------- ### Module Declaration for Global Router Type Inference Source: https://tanstack.com/router/latest/docs/decisions-on-dx.md Demonstrates using TypeScript's module declaration to register the Router instance globally. This allows type inference for router-related components like Link without explicit imports, improving scalability and maintainability. ```tsx // src/app.tsx declare module '@tanstack/react-router' { interface Register { router: typeof router } } ``` ```tsx export const PostsIdLink = () => { return ( <Link to="/posts/$postId" // ^? TypeScript will auto-complete this for you params={{ postId: '123' }} // and this too! > Go to post 123 </Link> ) } ``` -------------------------------- ### Define Menu Component with ValidateLinkOptionsArray (Solid) Source: https://tanstack.com/router/latest/docs/guide/type-utilities.md This Solid Menu component leverages ValidateLinkOptionsArray for type-safe navigation items. It uses Solid's For component for efficient rendering of the list. ```tsx import { For } from 'solid-js' export interface MenuProps< TRouter extends RegisteredRouter = RegisteredRouter, TItems extends ReadonlyArray<unknown> = ReadonlyArray<unknown>, > { items: ValidateLinkOptionsArray<TRouter, TItems> } export function Menu< TRouter extends RegisteredRouter = RegisteredRouter, TItems extends ReadonlyArray<unknown>, >(props: MenuProps<TRouter, TItems>): Solid.JSX.Element export function Menu(props: MenuProps): Solid.JSX.Element { return ( <ul> <For each={props.items}> {(item) => ( <li> <Link {...item} /> </li> )} </For> </ul> ) } ``` -------------------------------- ### Configure Esbuild for React with TanStack Router Source: https://tanstack.com/router/latest/docs/installation/with-esbuild.md Add the tanstackRouter plugin to your Esbuild configuration for React projects. Ensure autoCodeSplitting is enabled for optimized loading. ```javascript import { tanstackRouter } from '@tanstack/router-plugin/esbuild' export default { // ... plugins: [ tanstackRouter({ target: 'react', autoCodeSplitting: true, }), ], } ``` -------------------------------- ### Checking if a Specific Route is Rendered Source: https://tanstack.com/router/latest/docs/api/router/useMatchHook.md Illustrates how to use `useMatch` with `shouldThrow: false` to safely check if a specific route is currently rendered. ```APIDOC ## Example: Checking if a specific route is currently rendered ### Description This example shows how to use `useMatch` with the `shouldThrow: false` option to check if a particular route (e.g., `/posts`) is currently rendered. If not found, it returns `undefined`. ### Code ```tsx import { useMatch } from '@tanstack/react-router' function Component() { const match = useMatch({ from: '/posts', shouldThrow: false }) // match is of type RouteMatch | undefined if (match !== undefined) { // The '/posts' route is currently rendered // ... } } ``` ``` -------------------------------- ### Preload Route Matches (TypeScript) Source: https://tanstack.com/router/latest/docs/api/router/RouterType.md Preloads route matches based on provided navigation options. Preloaded matches are temporarily stored and are not persisted beyond the next navigation action. ```typescript type preloadRoute = (opts?: NavigateOptions) => Promise<RouteMatch[]> ``` -------------------------------- ### Inherit Search Params in Child Routes Source: https://tanstack.com/router/latest/docs/guide/search-params.md Demonstrates how child routes inherit and access search parameters defined in parent routes. ```tsx const productSearchSchema = z.object({ page: z.number().catch(1), filter: z.string().catch(''), sort: z.enum(['newest', 'oldest', 'price']).catch('newest'), }) type ProductSearch = z.infer<typeof productSearchSchema> export const Route = createFileRoute('/shop/products')({ validateSearch: productSearchSchema, }) ``` ```tsx export const Route = createFileRoute('/shop/products/$productId')({ beforeLoad: ({ search }) => { search // ^? ProductSearch ✅ }, }) ``` -------------------------------- ### Configure Route Remount Dependencies Source: https://tanstack.com/router/latest/docs/api/router/RouterOptionsType.md Shows how to define the defaultRemountDeps function to force route component remounting based on specific parameters or loader dependencies. ```tsx remountDeps: ({ params }) => params ``` -------------------------------- ### headers Method Source: https://tanstack.com/router/latest/docs/api/router/RouteOptionsType.md Specifies custom HTTP headers for SSR. ```APIDOC ## headers ### Description Allows specifying custom HTTP headers to be sent when this route is rendered during SSR. ### Parameters - **opts** (Object) - Required - Contains matches, match, params, and loaderData. ### Response - **Returns** (Promise<Record<string, string>> | Record<string, string>) - An object of header name/value pairs. ``` -------------------------------- ### Route.redirect (File-Based Routes) Source: https://tanstack.com/router/latest/docs/api/router/redirectFunction.md Illustrates using `Route.redirect` within file-based routing. This method automatically uses the route's path as the origin, enabling type-safe relative redirects. ```APIDOC ## Route.redirect (File-Based Routes) ### Description Used within file-based routes (`createFileRoute`), `Route.redirect` automatically infers the origin path, allowing for type-safe relative redirects. ### Method `Route.redirect(options: RedirectOptions)` ### Endpoint N/A (Used within route definitions) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (RedirectOptions) - Required - Options to determine the redirect behavior. - **to** (string) - Required - The relative or absolute route path to redirect to. - **throw** (boolean) - Optional - If true, the `Redirect` object will be thrown. Defaults to true when used in `beforeLoad` or `loader`. ### Request Example ```tsx // In routes/dashboard/settings.tsx import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/dashboard/settings')({ beforeLoad: ({ context }) => { if (!context.user) { // Relative redirect - automatically knows we're redirecting from '/dashboard/settings' throw Route.redirect({ to: '../login', // Redirects to '/dashboard/login' }) } }, loader: () => { // Also works in loader if (needsMigration) { throw Route.redirect({ to: './migrate', // Redirects to '/dashboard/settings/migrate' }) } }, }) ``` ### Response #### Success Response (200) N/A (This function triggers a redirect, not a typical response) #### Response Example N/A ``` -------------------------------- ### Configure Global Code Splitting in Vite Source: https://tanstack.com/router/latest/docs/guide/automatic-code-splitting.md Use the tanstackRouter plugin in your vite.config.ts to define default bundling behavior. This allows grouping specific route properties like components into a single chunk. ```ts import { defineConfig } from 'vite' import { tanstackRouter } from '@tanstack/router-plugin/vite' export default defineConfig({ plugins: [ tanstackRouter({ autoCodeSplitting: true, codeSplittingOptions: { defaultBehavior: [ ['component', 'pendingComponent', 'errorComponent', 'notFoundComponent'], ], }, }), ], }) ``` -------------------------------- ### Enable browser beforeunload protection Source: https://tanstack.com/router/latest/docs/guide/navigation-blocking.md Configure the enableBeforeUnload option to trigger the browser's native 'Are you sure you want to leave?' dialog during tab closing or page refreshes. ```tsx import { useBlocker } from '@tanstack/react-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = useState(false) useBlocker({ enableBeforeUnload: formIsDirty, }) } ``` ```tsx import { useBlocker } from '@tanstack/solid-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = useState(false) useBlocker({ enableBeforeUnload: formIsDirty(), }) } ``` -------------------------------- ### Create a root route Source: https://tanstack.com/router/latest/docs/routing/routing-concepts.md Define the top-most route in the tree using createRootRoute or createRootRouteWithContext for shared router context. ```tsx // Standard root route import { createRootRoute } from '@tanstack/react-router' export const Route = createRootRoute() // Root route with Context import { createRootRouteWithContext } from '@tanstack/react-router' import type { QueryClient } from '@tanstack/react-query' export interface MyRouterContext { queryClient: QueryClient } export const Route = createRootRouteWithContext<MyRouterContext>() ``` ```tsx // Standard root route import { createRootRoute } from '@tanstack/solid-router' export const Route = createRootRoute() // Root route with Context import { createRootRouteWithContext } from '@tanstack/solid-router' import type { QueryClient } from '@tanstack/solid-query' export interface MyRouterContext { queryClient: QueryClient } export const Route = createRootRouteWithContext<MyRouterContext>() ``` -------------------------------- ### Router API Functions Source: https://tanstack.com/router/latest/docs/api/router.md Explore the core functions available in the TanStack Router API for creating and managing routes. ```APIDOC ## Router API Functions ### Description Provides a set of functions for defining, creating, and manipulating routes within the TanStack Router. ### Functions - **`createFileRoute`**: Creates a file-based route. - **`createLazyFileRoute`**: Creates a lazy-loaded file-based route. - **`createRootRoute`**: Creates the root route of the router. - **`createRootRouteWithContext`**: Creates the root route with context. - **`createRoute`**: Creates a standard route. - **`createLazyRoute`**: Creates a lazy-loaded route. - **`createRouteMask`**: Creates a route mask for matching. - **`createRouter`**: Initializes and creates the router instance. - **`defer`**: Defers the resolution of a value. - **`getRouteApi`**: Retrieves the API for a given route. - **`isNotFound`**: Checks if a route match is a 'not found' scenario. - **`isRedirect`**: Checks if a route match is a redirect. - **`lazyRouteComponent`**: Lazily loads a route component. - **`linkOptions`**: Provides options for link generation. - **`notFound`**: Creates a 'not found' route definition. - **`redirect`**: Creates a redirect route definition. - **`retainSearchParams`**: Retains search parameters during navigation. - **`stripSearchParams`**: Strips search parameters from a URL. ### Example Usage (Conceptual) ```javascript import { createRootRoute, createRoute, createRouter } from '@tanstack/router' const rootRoute = createRootRoute() const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', component: () => <div>Hello World!</div> }) const routeTree = rootRoute.addChildren([indexRoute]) const router = createRouter({ routeTree }) // Render the router // router.mount() ``` ``` -------------------------------- ### lazyRouteComponent Function Source: https://tanstack.com/router/latest/docs/api/router/lazyRouteComponentFunction.md The lazyRouteComponent function allows for one-off code-split route components that can be preloaded. It's recommended to use createLazyFileRoute for file-based routing. ```APIDOC ## lazyRouteComponent Function ### Description The `lazyRouteComponent` function can be used to create a one-off code-split route component that can be preloaded using a `component.preload()` method. If you are using file-based routing, it's recommended to use the `createLazyFileRoute` function instead. ### Parameters #### `importer` Option - **Type**: `() => Promise<T>` - **Required**: Yes - **Description**: A function that returns a promise that resolves to an object containing the component to be loaded. #### `exportName` Option - **Type**: `string` - **Optional**: Yes - **Description**: The name of the component to be loaded from the imported object. Defaults to `'default'`. ### Returns - A `React.lazy` component that can be preloaded using a `component.preload()` method. ### Examples #### Default Export ```tsx import { lazyRouteComponent } from '@tanstack/react-router' const route = createRoute({ path: '/posts/$postId', component: lazyRouteComponent(() => import('./Post')) // default export }) ``` #### Named Export ```tsx import { lazyRouteComponent } from '@tanstack/react-router' const route = createRoute({ path: '/posts/$postId', component: lazyRouteComponent( () => import('./Post'), 'PostByIdPageComponent' // named export ) }) ``` ``` -------------------------------- ### Implement Role Hierarchy Source: https://tanstack.com/router/latest/docs/how-to/setup-rbac.md Use a mapping object to define role inheritance and check if a user possesses a required role. ```tsx const roleHierarchy = { admin: ['admin', 'moderator', 'user'], moderator: ['moderator', 'user'], user: ['user'], } const hasRole = (requiredRole: string) => { const userRoles = user?.roles || [] return userRoles.some((userRole) => roleHierarchy[userRole]?.includes(requiredRole), ) } ``` -------------------------------- ### Using Path Parameters in Solid Loaders Source: https://tanstack.com/router/latest/docs/guide/data-loading.md Access path parameters within your loader functions by destructuring them from the `params` property of the function's arguments. This allows dynamic data fetching based on the URL. ```tsx // src/routes/posts.$postId.tsx export const Route = createFileRoute('/posts/$postId')({ loader: ({ params: { postId } }) => fetchPostById(postId), }) ``` -------------------------------- ### Root Layout Component for TanStack Router Source: https://tanstack.com/router/latest/docs/installation/manual.md Defines the root layout component for the application, including navigation links and the TanStack Router Devtools. Requires React and TanStack Router. ```typescript import { createRootRoute, Link, Outlet } from '@tanstack/react-router' import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' const RootLayout = () => ( <> <div className="p-2 flex gap-2"> <Link to="/" className="[&.active]:font-bold"> Home </Link>{' '} <Link to="/about" className="[&.active]:font-bold"> About </Link> </div> <hr /> <Outlet /> <TanStackRouterDevtools /> </> ) export const Route = createRootRoute({ component: RootLayout }) ``` -------------------------------- ### HTML Language Attribute with Paraglide Source: https://tanstack.com/router/latest/docs/guide/internationalization-i18n.md Demonstrates how to set the HTML `lang` attribute dynamically using the `getLocale` function from Paraglide's runtime. This is crucial for SEO and accessibility. ```tsx import { getLocale } from '../paraglide/runtime' ;<html lang={getLocale()} /> ``` -------------------------------- ### Enable Automatic Code Splitting in Vite Source: https://tanstack.com/router/latest/docs/guide/code-splitting.md Configures the TanStack Router Vite plugin to automatically split route files into critical and non-critical chunks, improving initial load performance. ```typescript import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' export default defineConfig({ plugins: [ tanstackRouter({ autoCodeSplitting: true, }), react(), ], }) ``` -------------------------------- ### Define Root Route Context Source: https://tanstack.com/router/latest/docs/guide/router-context.md Use createRootRouteWithContext to define the shape of the router context for React or Solid. ```tsx import { createRootRouteWithContext } from '@tanstack/react-router' interface MyRouterContext { foo: boolean } export const Route = createRootRouteWithContext<MyRouterContext>()({ component: App, }) ``` ```tsx import { createRootRouteWithContext } from '@tanstack/solid-router' interface MyRouterContext { foo: boolean } export const Route = createRootRouteWithContext<MyRouterContext>()({ component: App, }) ``` -------------------------------- ### Clerk React Wrapper and Auth Hook Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Set up the ClerkProvider and create a custom hook `useClerkAuth` to adapt Clerk's authentication state to TanStack Router's context system. This hook normalizes user data and authentication status. ```tsx import { ClerkProvider, useUser, useAuth } from '@clerk/clerk-react' export function ClerkWrapper({ children }: { children: React.ReactNode }) { return ( <ClerkProvider publishableKey={import.meta.env.VITE_CLERK_PUBLISHABLE_KEY}> {children} </ClerkProvider> ) } export function useClerkAuth() { const { isSignedIn, isLoaded } = useAuth() const { user } = useUser() return { isAuthenticated: isSignedIn, user: user ? { id: user.id, username: user.username || user.primaryEmailAddress?.emailAddress || '', email: user.primaryEmailAddress?.emailAddress || '', } : null, isLoading: !isLoaded, login: () => { // Clerk handles login through components window.location.href = '/sign-in' }, logout: () => { // Clerk handles logout through components window.location.href = '/sign-out' }, } } ``` -------------------------------- ### Preload Route API Source: https://tanstack.com/router/latest/docs/api/router/RouterType.md Preloads route matches based on navigation options without committing them to history. Useful for performance optimizations. ```APIDOC ## preloadRoute Method ### Description Preloads all of the matches that match the provided `NavigateOptions`. ### Method `preloadRoute` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **opts** (NavigateOptions) - Optional, defaults to the current location. - The options that will be used to determine which route matches to preload. ### Request Example ```json { "to": "/settings", "params": { "section": "profile" } } ``` ### Response #### Success Response (200) - **RouteMatch[]** - An array of all of the route matches that were preloaded. #### Response Example ```json [ { "id": "/settings", "params": {"section": "profile"}, "routeId": "settings", "pathname": "/settings", "search": "", "hash": "", "state": {}, "data": {}, "error": null, "status": "success" } ] ``` ``` -------------------------------- ### API Reference: `LocationRewriteFunction` type Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Describes the `LocationRewriteFunction` type, including its parameters (`url`) and possible return values (`URL`, `string`, `undefined`). ```APIDOC ### `LocationRewriteFunction` type ```tsx type LocationRewriteFunction = (opts: { url: URL }) => undefined | string | URL ``` **Parameters:** - `url`: A `URL` object representing the current URL **Returns:** - `URL`: The transformed URL object (can be the same mutated object or a new instance) - `string`: A full href string that will be parsed into a URL - `undefined`: Skip the rewrite, use the original URL ``` -------------------------------- ### Route.useSearch Hook Source: https://tanstack.com/router/latest/docs/guide/render-optimizations.md Accessing and subscribing to search parameters with fine-grained control and structural sharing. ```APIDOC ## GET Route.useSearch ### Description Accesses the current route search parameters. Supports partial subscriptions via the select property and structural sharing to prevent unnecessary re-renders. ### Method HOOK ### Parameters #### Options - **select** (function) - Optional - A selector function to pick specific parts of the search state. - **structuralSharing** (boolean) - Optional - Enables referential equality checks for the returned object. Defaults to false. ### Request Example ```tsx const result = Route.useSearch({ select: (search) => ({ foo: search.foo }), structuralSharing: true }) ``` ### Response - **result** (any) - The selected and structurally shared search state. ``` -------------------------------- ### Matching Route with MatchRoute Component (Function Children) Source: https://tanstack.com/router/latest/docs/guide/navigation.md Use the `<MatchRoute>` component with a function as children to render content conditionally when a route is matched. It accepts `pending` to check for pending transitions. ```tsx function Component() { return ( <div> <Link to="/users"> Users <MatchRoute to="/users" pending> {(match) => { return <Spinner show={match} /> }} </MatchRoute> </Link> </div> ) } ``` -------------------------------- ### Conditional Rendering with MatchRoute Source: https://tanstack.com/router/latest/docs/api/router/matchRouteComponent.md Demonstrates how to use the MatchRoute component to conditionally render a Spinner component when a specific route ('/posts/$postId') is matched. The children prop is a function that receives the matched parameters or false, controlling the Spinner's visibility. ```tsx import { MatchRoute } from '@tanstack/react-router' function Component() { return ( <div> <MatchRoute to="/posts/$postId" params={{ postId: '123' }} pending> {(match) => <Spinner show={!!match} wait="delay-50" />} </MatchRoute> </div> ) } ``` -------------------------------- ### Create Permissions Hook Source: https://tanstack.com/router/latest/docs/how-to/setup-rbac.md A custom hook to access authentication-related functions and user data from the router's context. It simplifies permission checking logic within components. ```tsx import { useRouter } from '@tanstack/react-router' export function usePermissions() { const router = useRouter() const auth = router.options.context.auth return { hasRole: auth.hasRole, hasAnyRole: auth.hasAnyRole, hasPermission: auth.hasPermission, hasAnyPermission: auth.hasAnyPermission, user: auth.user, } } ``` -------------------------------- ### Wrap Inner Router Content with Context Source: https://tanstack.com/router/latest/docs/api/router/RouterOptionsType.md Demonstrates using the InnerWrap property to wrap router contents, allowing access to router-specific hooks like useRouterState within the provider. ```tsx import { createRouter } from '@tanstack/react-router' const router = createRouter({ // ... InnerWrap: ({ children }) => { const routerState = useRouterState() return ( <MyContext.Provider value={myContext}> {children} </MyContext.Provider> ) }, }) ``` -------------------------------- ### SSR Streaming Deferred Data Lifecycle (React) Source: https://tanstack.com/router/latest/docs/guide/deferred-data-loading.md This section outlines the Server-Side Rendering (SSR) and streaming deferred data lifecycle with TanStack Router in React. It details how promises are tracked on the server, serialized, and streamed to the client, enabling progressive rendering and data hydration. ```markdown ## SSR & Streaming Deferred Data **Streaming requires a server that supports it and for TanStack Router to be configured to use it properly.** Please read the entire [Streaming SSR Guide](./ssr.md#streaming-ssr) for step by step instructions on how to set up your server for streaming. ## SSR Streaming Lifecycle The following is a high-level overview of how deferred data streaming works with TanStack Router: - Server - Promises are marked and tracked as they are returned from route loaders - All loaders resolve and any deferred promises are serialized and embedded into the html - The route begins to render - Deferred promises rendered with the `<Await>` component trigger suspense boundaries, allowing the server to stream html up to that point - Client - The client receives the initial html from the server - `<Await>` components suspend with placeholder promises while they wait for their data to resolve on the server - Server - As deferred promises resolve, their results (or errors) are serialized and streamed to the client via an inline script tag - The resolved `<Await>` components and their suspense boundaries are resolved and their resulting HTML is streamed to the client along with their dehydrated data - Client - The suspended placeholder promises within `<Await>` are resolved with the streamed data/error responses and either render the result or throw the error to the nearest error boundary ``` -------------------------------- ### Create dynamic links Source: https://tanstack.com/router/latest/docs/guide/navigation.md Usage of the Link component with dynamic route segments and parameters. ```tsx const link = ( <Link to="/blog/post/$postId" params={{ postId: 'my-first-blog-post', }} > Blog Post </Link> ) ``` -------------------------------- ### Define ToOptions and ToMaskOptions Interfaces Source: https://tanstack.com/router/latest/docs/guide/navigation.md The core interfaces used for navigation and route matching across the library. These define the structure for specifying origin, destination, and associated URL data. ```typescript type ToOptions< TRouteTree extends AnyRoute = AnyRoute, TFrom extends RoutePaths<TRouteTree> | string = string, TTo extends string = '', > = { // `from` is an optional route ID or path. If it is not supplied, only absolute paths will be auto-completed and type-safe. It's common to supply the route.fullPath of the origin route you are rendering from for convenience. If you don't know the origin route, leave this empty and work with absolute paths or unsafe relative paths. from?: string // `to` can be an absolute route path or a relative path from the `from` option to a valid route path. ⚠️ Do not interpolate path params, hash or search params into the `to` options. Use the `params`, `search`, and `hash` options instead. to: string // `params` is either an object of path params to interpolate into the `to` option or a function that supplies the previous params and allows you to return new ones. This is the only way to interpolate dynamic parameters into the final URL. Depending on the `from` and `to` route, you may need to supply none, some or all of the path params. TypeScript will notify you of the required params if there are any. params: | Record<string, unknown> | ((prevParams: Record<string, unknown>) => Record<string, unknown>) // `search` is either an object of query params or a function that supplies the previous search and allows you to return new ones. Depending on the `from` and `to` route, you may need to supply none, some or all of the query params. TypeScript will notify you of the required search params if there are any. search: | Record<string, unknown> | ((prevSearch: Record<string, unknown>) => Record<string, unknown>) // `hash` is either a string or a function that supplies the previous hash and allows you to return a new one. hash?: string | ((prevHash: string) => string) // `state` is either an object of state or a function that supplies the previous state and allows you to return a new one. State is stored in the history API and can be useful for passing data between routes that you do not want to permanently store in URL search params. state?: | Record<string, any> | ((prevState: Record<string, unknown>) => Record<string, unknown>) // `mask` is another navigation object used to mask the URL shown in the browser for this navigation. mask?: ToMaskOptions<TRouteTree> } type ToMaskOptions<TRouteTree extends AnyRoute = AnyRoute> = { // `from`, `to`, `params`, `search`, `hash`, and `state` behave the same as in `ToOptions`. // `mask` itself is not allowed inside `ToMaskOptions`. from?: string to: string params: | Record<string, unknown> | ((prevParams: Record<string, unknown>) => Record<string, unknown>) search: | Record<string, unknown> | ((prevSearch: Record<string, unknown>) => Record<string, unknown>) hash?: string | ((prevHash: string) => string) state?: | Record<string, any> | ((prevState: Record<string, unknown>) => Record<string, unknown>) // If true, the URL will unmask on page reload. unmaskOnReload?: boolean } ``` -------------------------------- ### Configure Webpack for TanStack Router Source: https://tanstack.com/router/latest/docs/installation/with-webpack.md Add the tanstackRouter plugin to your webpack configuration. Specify the target framework and enable autoCodeSplitting. ```ts import { tanstackRouter } from '@tanstack/router-plugin/webpack' export default { plugins: [ tanstackRouter({ target: 'react', autoCodeSplitting: true, }), ], } ``` ```ts import { tanstackRouter } from '@tanstack/router-plugin/webpack' export default { plugins: [ tanstackRouter({ target: 'solid', autoCodeSplitting: true, }), ], } ``` -------------------------------- ### Merge Physical Routes at Current Level Source: https://tanstack.com/router/latest/docs/routing/virtual-file-routes.md Use `physical` with an empty path prefix or a single argument to merge routes from a physical directory at the current level without adding a path prefix. Imports are required. ```typescript // routes.ts import { physical, rootRoute, route } from '@tanstack/virtual-file-routes' export const routes = rootRoute('__root.tsx', [ route('/about', 'about.tsx'), // Merge features/ routes at root level (no path prefix) physical('features'), // Or equivalently: physical('', 'features') ]) ``` -------------------------------- ### Using useMatches Hook - React Source: https://tanstack.com/router/latest/docs/api/router/useMatchesHook.md Demonstrates how to import and use the useMatches hook within a React component to access route match data. The hook returns an array of RouteMatch objects. ```tsx import { useMatches } from '@tanstack/react-router' function Component() { const matches = useMatches() // ^? [RouteMatch, RouteMatch, ...] // ... } ``` -------------------------------- ### Strip Search Parameters in TanStack Router Source: https://tanstack.com/router/latest/docs/api/router/stripSearchParamsFunction.md Demonstrates three ways to use stripSearchParams: removing default values via an object, removing specific keys by name, and stripping all search parameters entirely using a boolean flag. ```tsx import { z } from 'zod' import { createFileRoute, stripSearchParams } from '@tanstack/react-router' const defaultValues = { one: 'abc', two: 'xyz', } const searchSchema = z.object({ one: z.string().default(defaultValues.one), two: z.string().default(defaultValues.two), }) export const Route = createFileRoute('/')({ validateSearch: searchSchema, search: { middlewares: [stripSearchParams(defaultValues)], }, }) ``` ```tsx import { z } from 'zod' import { createRootRoute, stripSearchParams } from '@tanstack/react-router' const searchSchema = z.object({ hello: z.string().default('world'), requiredParam: z.string(), }) export const Route = createRootRoute({ validateSearch: searchSchema, search: { middlewares: [stripSearchParams(['hello'])], }, }) ``` ```tsx import { z } from 'zod' import { createFileRoute, stripSearchParams } from '@tanstack/react-router' const searchSchema = z.object({ one: z.string().default('abc'), two: z.string().default('xyz'), }) export const Route = createFileRoute('/')({ validateSearch: searchSchema, search: { middlewares: [stripSearchParams(true)], }, }) ``` -------------------------------- ### Configure typescript-eslint to Allow TanStack Router Exceptions Source: https://tanstack.com/router/latest/docs/eslint/eslint-plugin-router.md Adjust the `@typescript-eslint/only-throw-error` rule to allow `Redirect` and `NotFoundError` from `@tanstack/router-core` to be thrown. This prevents conflicts with TanStack Router's error handling. ```json { "rules": { "@typescript-eslint/only-throw-error": [ "error", { "allow": [ { "from": "package", "package": "@tanstack/router-core", "name": "Redirect" }, { "from": "package", "package": "@tanstack/router-core", "name": "NotFoundError" } ] } ] } } ``` -------------------------------- ### Loader Parameters Source: https://tanstack.com/router/latest/docs/guide/data-loading.md The `loader` function in TanStack Router receives a single object containing various properties to access route and location information. ```APIDOC ## `loader` Parameters The `loader` function receives a single object with the following properties: - `abortController` - The route's abortController. Its signal is cancelled when the route is unloaded or when the Route is no longer relevant and the current invocation of the `loader` function becomes outdated. - `cause` - The cause of the current route match. Can be either one of the following: - `enter` - When the route is matched and loaded after not being matched in the previous location. - `preload` - When the route is being preloaded. - `stay` - When the route is matched and loaded after being matched in the previous location. - `context` - The route's context object, which is a merged union of: - Parent route context - This route's context as provided by the `beforeLoad` option - `deps` - The object value returned from the `Route.loaderDeps` function. If `Route.loaderDeps` is not defined, an empty object will be provided instead. - `location` - The current location - `params` - The route's path params - `parentMatchPromise` - `Promise<RouteMatch>` (`undefined` for the root route) - `preload` - Boolean which is `true` when the route is being preloaded instead of loaded - `route` - The route itself ``` -------------------------------- ### Define loaderDeps for search parameters Source: https://tanstack.com/router/latest/docs/guide/data-loading.md Use loaderDeps to explicitly track search parameters, ensuring the route reloads only when relevant dependencies change. ```tsx // /routes/posts.tsx export const Route = createFileRoute('/posts')({ loaderDeps: ({ search: { offset, limit } }) => ({ offset, limit }), loader: ({ deps: { offset, limit } }) => fetchPosts({ offset, limit, }), }) ``` -------------------------------- ### Handle Auth0 Redirects in Authenticated Route Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Use this pattern in an authenticated route's beforeLoad hook to trigger the Auth0 login flow without throwing a redirect, preventing infinite loops. ```tsx export const Route = createFileRoute('/_authenticated')({ beforeLoad: ({ context }) => { if (!context.auth.isAuthenticated && !context.auth.isLoading) { context.auth.login() // Don't throw redirect, let Auth0 handle it return } }, component: () => <Outlet />, }) ``` -------------------------------- ### Auth0 React Wrapper Component Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Create a custom wrapper component for Auth0 using Auth0Provider and a custom context. This component provides authentication state and functions to the application. ```tsx import { Auth0Provider, useAuth0 } from '@auth0/auth0-react' import { createContext, useContext } from 'react' interface Auth0ContextType { isAuthenticated: boolean user: any login: () => void logout: () => void isLoading: boolean } const Auth0Context = createContext<Auth0ContextType | undefined>(undefined) export function Auth0Wrapper({ children }: { children: React.ReactNode }) { return ( <Auth0Provider domain={import.meta.env.VITE_AUTH0_DOMAIN} clientId={import.meta.env.VITE_AUTH0_CLIENT_ID} authorizationParams={{ redirect_uri: window.location.origin, }} > <Auth0ContextProvider>{children}</Auth0ContextProvider> </Auth0Provider> ) } function Auth0ContextProvider({ children }: { children: React.ReactNode }) { const { isAuthenticated, user, loginWithRedirect, logout, isLoading } = useAuth0() const contextValue = { isAuthenticated, user, login: loginWithRedirect, logout: () => logout({ logoutParams: { returnTo: window.location.origin } }), isLoading, } return ( <Auth0Context.Provider value={contextValue}> {children} </Auth0Context.Provider> ) } export function useAuth0Context() { const context = useContext(Auth0Context) if (context === undefined) { throw new Error('useAuth0Context must be used within Auth0Wrapper') } return context } ``` -------------------------------- ### Optional Parameter Inheritance and Removal Source: https://tanstack.com/router/latest/docs/guide/navigation.md Demonstrates inheriting current parameters or explicitly removing them by setting them to undefined. ```tsx // Inherits current route parameters <Link to="/posts/{-$category}" params={{}}> All Posts </Link> ``` ```tsx // Removes the category parameter <Link to="/posts/{-$category}" params={{ category: undefined }}> All Posts </Link> ``` -------------------------------- ### RouteApi - useMatch Method Source: https://tanstack.com/router/latest/docs/api/router/RouteApiType.md Provides a type-safe version of the `useMatch` hook, pre-bound to a specific route ID. ```APIDOC ## RouteApi - useMatch Method ### Description A type-safe version of the `useMatch` hook that is pre-bound to the route ID that the `RouteApi` instance was created with. ### Method `useMatch<TSelected = TAllContext>(opts?: { select?: (match: TAllContext) => TSelected }): TSelected` ### Parameters #### Options - **opts.select** (function) - Optional - If supplied, this function will be called with the route match and the return value will be returned from `useMatch`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks. - **opts.structuralSharing** (boolean) - Optional - Configures whether structural sharing is enabled for the value returned by `select`. See the [Render Optimizations guide](../../guide/render-optimizations.md) for more information. ### Returns - If a `select` function is provided, the return value of the `select` function. - If no `select` function is provided, the `RouteMatch` object or a loosened version of the `RouteMatch` object if `opts.strict` is `false`. ``` -------------------------------- ### Narrow Link Routes for Performance Source: https://tanstack.com/router/latest/docs/guide/type-safety.md Use the 'from' or 'to' props in Link components to narrow route resolution and reduce TypeScript check times. ```tsx <Link to=".." search={{ page: 0 }} /> <Link to="." search={{ page: 0 }} /> ``` ```tsx <Link from={Route.fullPath} to=".." search={{page: 0}} /> <Link from="/posts" to=".." search={{page: 0}} /> ``` ```tsx const from: '/posts/$postId/deep' | '/posts/' = '/posts/' <Link from={from} to='..' /> ``` ```tsx const from = '/posts' <Link from={from} to='..' /> ``` -------------------------------- ### Update App Configuration with Supabase Auth Provider Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Integrates the Supabase authentication provider with the TanStack Router by wrapping the `RouterProvider` with `SupabaseAuthProvider` and passing auth context. ```tsx import { RouterProvider } from '@tanstack/react-router' import { SupabaseAuthProvider, useSupabaseAuth } from './auth/supabase' import { router } from './router' function InnerApp() { const auth = useSupabaseAuth() if (auth.isLoading) { return ( <div className="flex items-center justify-center min-h-screen"> Loading... </div> ) } return <RouterProvider router={router} context={{ auth }} /> } function App() { return ( <SupabaseAuthProvider> <InnerApp /> </SupabaseAuthProvider> ) } export default App ``` -------------------------------- ### Sorted route tree structure Source: https://tanstack.com/router/latest/docs/routing/route-matching.md The resulting route tree after TanStack Router applies its sorting logic. ```text Root - / - about/us - about - blog - / - new - $postId - * ``` -------------------------------- ### Accessing Route APIs with getRouteApi in React Source: https://tanstack.com/router/latest/docs/guide/code-splitting.md Shows how to use the getRouteApi helper function in React to access type-safe route APIs like useLoaderData, useParams, etc., from a component file without directly importing the route. ```tsx import { createRoute } from '@tanstack/react-router' import { MyComponent } from './MyComponent' const route = createRoute({ path: '/my-route', loader: () => ({ foo: 'bar', }), component: MyComponent, }) ``` ```tsx import { getRouteApi } from '@tanstack/react-router' const route = getRouteApi('/my-route') export function MyComponent() { const loaderData = route.useLoaderData() // ^? { foo: string } return <div>...</div> } ``` -------------------------------- ### Define Route Suffixes Source: https://tanstack.com/router/latest/docs/guide/path-params.md Matches URL segments ending with a static suffix after a dynamic parameter. ```tsx export const Route = createFileRoute('/files/{$fileName}.txt')({ component: FileComponent, }) function FileComponent() { const { fileName } = Route.useParams() // fileName will be the value before 'txt' return <div>File Name: {fileName}</div> } ``` ```tsx export const Route = createFileRoute('/files/{$fileName}.txt')({ component: FileComponent, }) function FileComponent() { const params = Route.useParams() // fileName will be the value before 'txt' return <div>File Name: {params().fileName}</div> } ``` -------------------------------- ### User Permissions Access Control Source: https://tanstack.com/router/latest/docs/how-to/setup-rbac.md This route requires the user to have 'users:read' and 'users:write' permissions. If not, it redirects to an unauthorized page. ```typescript import { createFileRoute, redirect, Outlet } from '@tanstack/react-router' export const Route = createFileRoute('/_authenticated/_users')({ beforeLoad: ({ context, location }) => { const requiredPermissions = ['users:read', 'users:write'] if (!context.auth.hasAnyPermission(requiredPermissions)) { throw redirect({ to: '/unauthorized', search: { redirect: location.href, reason: 'insufficient_permissions', }, }) } }, component: () => <Outlet />, }) ``` -------------------------------- ### Implement HeadContent in Single-Page Applications Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md Render the HeadContent component at the top of the component tree for single-page applications to manage head tags dynamically. ```tsx import { HeadContent } from '@tanstack/react-router' const rootRoute = createRootRoute({ component: () => ( <> <HeadContent /> <Outlet /> </> ), }) ``` ```tsx import { HeadContent } from '@tanstack/solid-router' const rootRoute = createRootRoute({ component: () => ( <> <HeadContent /> <Outlet /> </> ), }) ``` -------------------------------- ### Generate Page Title from Context Source: https://tanstack.com/router/latest/docs/guide/router-context.md Use the matched route context to dynamically set the document title. ```tsx export const Route = createRootRoute({ component: () => { const matches = useRouterState({ select: (s) => s.matches }) const matchWithTitle = [...matches] .reverse() .find((d) => d.context.getTitle) const title = matchWithTitle?.context.getTitle() || 'My App' return ( <html> <head> <title>{title} {/* ... */} ) }, }) ``` -------------------------------- ### useMatch Hook Overview Source: https://tanstack.com/router/latest/docs/api/router/useMatchHook.md The `useMatch` hook returns a `RouteMatch` object from the component tree. It provides access to route information and powers other hooks like `useParams` and `useLoaderData`. ```APIDOC ## useMatch Hook ### Description The `useMatch` hook returns a [`RouteMatch`](./RouteMatchType.md) object from the component tree. It provides access to route information and powers other hooks like `useParams`, `useLoaderData`, `useRouteContext`, and `useSearch`. ### Options The `useMatch` hook accepts a single argument, an `options` object with the following properties: #### `opts.from` - **Type**: `string` - **Description**: The route id of a match. Optional, but recommended for full type safety. If `opts.strict` is `true`, `from` is required. #### `opts.strict` - **Type**: `boolean` - **Description**: Optional. Defaults to `true`. If `false`, `opts.from` must not be set, and types will be loosened to `Partial`. #### `opts.select` - **Type**: `(match: RouteMatch) => TSelected` - **Description**: Optional. A function that will be called with the route match. Its return value will be returned from `useMatch` and used for shallow equality checks. #### `opts.structuralSharing` - **Type**: `boolean` - **Description**: Optional. Configures whether structural sharing is enabled for the value returned by `select`. #### `opts.shouldThrow` - **Type**: `boolean` - **Description**: Optional. Defaults to `true`. If `false`, `useMatch` will return `undefined` instead of throwing an error if a match is not found. ### Returns - If a `select` function is provided, the return value of the `select` function. - If no `select` function is provided, the [`RouteMatch`](./RouteMatchType.md) object or a loosened version if `opts.strict` is `false`. ``` -------------------------------- ### Create MUI Button Link Source: https://tanstack.com/router/latest/docs/guide/custom-link.md Configures an MUI Button to act as a router link by setting the component prop to 'a'. This enables button-styled navigation within the application. ```tsx import React from 'react' import { createLink } from '@tanstack/react-router' import { Button } from '@mui/material' import type { ButtonProps } from '@mui/material' import type { LinkComponent } from '@tanstack/react-router' interface MUIButtonLinkProps extends ButtonProps<'a'> {} const MUIButtonLinkComponent = React.forwardRef( (props, ref) => ) } ``` ``` -------------------------------- ### Synchronous Router Invalidation Source: https://tanstack.com/router/latest/docs/guide/data-mutations.md Shows how to await the completion of all route loaders after a mutation by passing the sync option to router.invalidate(). ```typescript const router = useRouter() const addTodo = async (todo: Todo) => { try { await api.addTodo() await router.invalidate({ sync: true }) } catch { // } } ``` -------------------------------- ### Update App Configuration with Clerk Auth Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md Integrates Clerk authentication context into the main App component. It handles loading states and provides authentication context to the router. ```tsx import { RouterProvider } from '@tanstack/react-router' import { ClerkWrapper, useClerkAuth } from './auth/clerk' import { router } from './router' function InnerApp() { const auth = useClerkAuth() if (auth.isLoading) { return (
Loading...
) } return } function App() { return ( ) } export default App ``` -------------------------------- ### Define a Virtual Route without a File Name Source: https://tanstack.com/router/latest/docs/routing/virtual-file-routes.md Create a virtual route without a file name to set a common path prefix for its children. Imports are required. ```typescript import { route } from '@tanstack/virtual-file-routes' export const routes = rootRoute('root.tsx', [ route('/hello', [ route('/world', 'world.tsx'), // full path will be "/hello/world" route('/universe', 'universe.tsx'), // full path will be "/hello/universe" ]), ]) ``` -------------------------------- ### Define fetch utility Source: https://tanstack.com/router/latest/docs/guide/data-loading.md A basic fetch utility function for retrieving post data. ```tsx export const fetchPosts = async () => { const res = await fetch(`/api/posts?page=${pageIndex}`) if (!res.ok) throw new Error('Failed to fetch posts') return res.json() } ``` -------------------------------- ### Configure HeadContent Asset Cross-Origin Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md Set cross-origin policies for manifest-managed assets like modulepreload and stylesheets using the assetCrossOrigin prop on the HeadContent component. ```tsx ``` -------------------------------- ### Index Route Component Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-location.md Define the component for the index route ('/'). This is the default component rendered when the root path is accessed. ```tsx import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/')({ component: Index, }) ``` -------------------------------- ### Using useRouterState Hook in React Source: https://tanstack.com/router/latest/docs/api/router/useRouterStateHook.md Demonstrates how to use the useRouterState hook in a React component to access the router's state. It shows both accessing the full state object and selecting specific parts of the state using the `select` option. ```tsx import { useRouterState } from '@tanstack/react-router' function Component() { const state = useRouterState() // ^ RouterState // OR const selected = useRouterState({ select: (state) => state.location, }) // ^ ParsedLocation // ... } ``` -------------------------------- ### Register Router Types Source: https://tanstack.com/router/latest/docs/guide/creating-a-router.md Uses TypeScript declaration merging to register the router instance, enabling full type safety across the project. ```tsx declare module '@tanstack/react-router' { interface Register { router: typeof router } } ``` ```tsx declare module '@tanstack/solid-router' { interface Register { router: typeof router } } ``` -------------------------------- ### RouterState Type Definition Source: https://tanstack.com/router/latest/docs/api/router/RouterStateType.md Overview of the RouterState object structure and its properties. ```APIDOC ## RouterState Type ### Description The `RouterState` type represents the internal state of the TanStack Router, providing visibility into pending matches, loading states, and location data. ### Properties - **status** ('pending' | 'idle') - The current status of the router. - **isLoading** (boolean) - True if the router is currently loading a route. - **isTransitioning** (boolean) - True if the router is currently transitioning to a new route. - **matches** (Array) - An array of all resolved and active route matches. - **location** (ParsedLocation) - The latest location parsed from browser history. - **resolvedLocation** (ParsedLocation) - The location that has been fully resolved and loaded. ### Type Definition ```typescript type RouterState = { status: 'pending' | 'idle' isLoading: boolean isTransitioning: boolean matches: Array location: ParsedLocation resolvedLocation: ParsedLocation } ``` ``` -------------------------------- ### Import TanStack Router Devtools Panel (React) Source: https://tanstack.com/router/latest/docs/devtools.md Imports the TanStack Router Devtools Panel component for React applications. This component is essential for displaying the router's debugging information. ```tsx import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools' ``` -------------------------------- ### Define Route Loader Function Source: https://tanstack.com/router/latest/docs/guide/data-loading.md Use a simple function for your route loader. Ensure the function is exported from the route file. ```tsx export const Route = createFileRoute('/posts')({ loader: () => fetchPosts(), }) ``` -------------------------------- ### Link with Hash Fragment Source: https://tanstack.com/router/latest/docs/guide/navigation.md Links to a specific section of a page using the hash prop. ```tsx const link = ( Section 1 ) ``` -------------------------------- ### Override Default Preloading with External Caching Libraries (React, Solid) Source: https://tanstack.com/router/latest/docs/guide/preloading.md This configuration bypasses TanStack Router's built-in caching by setting defaultPreloadStaleTime to 0. This allows external libraries like React Query to manage data freshness and loading, ensuring loaders are always invoked. ```tsx import { createRouter } from '@tanstack/react-router' const router = createRouter({ // ... defaultPreloadStaleTime: 0, }) ``` ```tsx import { createRouter } from '@tanstack/solid-router' const router = createRouter({ // ... defaultPreloadStaleTime: 0, }) ``` -------------------------------- ### Solid Language Switcher Component Source: https://tanstack.com/router/latest/docs/guide/path-params.md A Solid component for switching between different languages. It dynamically updates the locale parameter in the URL, removing 'en' for cleaner URLs. ```tsx function LanguageSwitcher() { const currentParams = useParams({ strict: false }) const languages = [ { code: 'en', name: 'English' }, { code: 'fr', name: 'Français' }, { code: 'es', name: 'Español' }, ] return (
{languages.map(({ code, name }) => ( ({ ...prev, locale: code === 'en' ? undefined : code, // Remove 'en' for clean URLs })} class={currentParams().locale === code ? 'active' : ''} > {name} ))}
) } ``` -------------------------------- ### Control Layout Visibility with Static Data Source: https://tanstack.com/router/latest/docs/guide/static-route-data.md Uses static data to conditionally render layout components based on route configuration. ```tsx function RootComponent() { const showNavbar = useMatches({ select: (matches) => !matches.some((m) => m.staticData?.showNavbar === false), }) return showNavbar ? : } ``` -------------------------------- ### Configure Auto Code Splitting in Vite Source: https://tanstack.com/router/latest/docs/guide/automatic-code-splitting.md This configuration enables auto code splitting within the TanStack Router Vite plugin. It demonstrates how to define custom chunking behavior for loaders and components. ```typescript import { defineConfig } from 'vite' import { tanstackRouter } from '@tanstack/router-plugin/vite' export default defineConfig({ plugins: [ tanstackRouter({ autoCodeSplitting: true, codeSplittingOptions: { defaultBehavior: [ ['loader'], ['component'], ], }, }), ], }) ``` -------------------------------- ### Create Typed Root Route (React) Source: https://tanstack.com/router/latest/docs/guide/router-context.md Use `createRootRouteWithContext` to define a typed root router context for your React application. This allows for type safety when injecting dependencies. ```tsx import { createRootRouteWithContext, createRouter, } from '@tanstack/react-router' interface MyRouterContext { user: User } // Use the routerContext to create your root route const rootRoute = createRootRouteWithContext()({ component: App, }) const routeTree = rootRoute.addChildren([ // ... ]) // Use the routerContext to create your router const router = createRouter({ routeTree, }) ``` -------------------------------- ### Optimize Loader Type Inference Source: https://tanstack.com/router/latest/docs/guide/type-safety.md Avoid inferring complex loader return types by explicitly returning Promise to improve TypeScript performance. ```tsx export const Route = createFileRoute('/posts/$postId/deep')({ loader: ({ context: { queryClient }, params: { postId } }) => queryClient.ensureQueryData(postQueryOptions(postId)), component: PostDeepComponent, }) function PostDeepComponent() { const params = Route.useParams() const data = useSuspenseQuery(postQueryOptions(params.postId)) return <> } ``` ```tsx export const Route = createFileRoute('/posts/$postId/deep')({ loader: async ({ context: { queryClient }, params: { postId } }) => { await queryClient.ensureQueryData(postQueryOptions(postId)) }, component: PostDeepComponent, }) function PostDeepComponent() { const params = Route.useParams() const data = useSuspenseQuery(postQueryOptions(params.postId)) return <> } ``` -------------------------------- ### Nested Object Route Definition (Not Scalable) Source: https://tanstack.com/router/latest/docs/decisions-on-dx.md Illustrates defining routes as a tree of nested objects. While visually intuitive, this approach is not scalable for large applications and complicates code-splitting. ```tsx const router = createRouter({ routes: { posts: { component: PostsPage, // /posts children: { $postId: { component: PostIdPage, // /posts/$postId }, }, }, // ... }, }) ``` -------------------------------- ### Accessing the root route match Source: https://tanstack.com/router/latest/docs/api/router/useMatchHook.md Shows how to retrieve the root route match using the exported rootRouteId constant, which is useful for accessing global route context. ```tsx import { useMatch, rootRouteId } from '@tanstack/react-router' function Component() { const match = useMatch({ from: rootRouteId }) } ``` -------------------------------- ### Solid Advanced Language Switcher Component Source: https://tanstack.com/router/latest/docs/guide/path-params.md A Solid component for advanced language switching. It includes a handler to update the locale parameter, omitting 'en' for cleaner URLs. ```tsx function AdvancedLanguageSwitcher() { const currentParams = useParams({ strict: false }) const handleLanguageChange = (newLocale: string) => { return (prev: any) => { // Preserve all existing params but update locale const updatedParams = { ...prev } if (newLocale === 'en') { // Remove locale for clean English URLs delete updatedParams.locale } else { updatedParams.locale = newLocale } return updatedParams } } return (
Français Español English
) } ``` -------------------------------- ### Index Route Component for TanStack Router Source: https://tanstack.com/router/latest/docs/installation/manual.md Defines the component for the index route ('/'). Requires TanStack Router. ```typescript import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/')({ component: Index, }) function Index() { return (

Welcome Home!

) } ``` -------------------------------- ### RouteApi - useRouteContext Method Source: https://tanstack.com/router/latest/docs/api/router/RouteApiType.md Provides a type-safe version of the `useRouteContext` hook, pre-bound to a specific route ID. ```APIDOC ## RouteApi - useRouteContext Method ### Description A type-safe version of the `useRouteContext` hook that is pre-bound to the route ID that the `RouteApi` instance was created with. ### Method `useRouteContext(opts?: { select?: (search: TAllContext) => TSelected }): TSelected` ### Parameters #### Options - **opts.select** (function) - Optional - If supplied, this function will be called with the route match and the return value will be returned from `useRouteContext`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks. ### Returns - If a `select` function is provided, the return value of the `select` function. - If no `select` function is provided, the `RouteContext` object or a loosened version of the `RouteContext` object if `opts.strict` is `false`. ``` -------------------------------- ### useBlocker Hook Source: https://tanstack.com/router/latest/docs/api/router/useBlockerHook.md The useBlocker hook allows you to block navigation when a specific condition is met. It accepts an options object with properties like `shouldBlockFn`, `disabled`, `enableBeforeUnload`, and `withResolver`. ```APIDOC ## useBlocker Hook ### Description The `useBlocker` hook is used to block navigation when a specified condition is met. It's an experimental feature. ### Method `useBlocker(options)` ### Parameters #### Request Body (options object) - **shouldBlockFn** (`ShouldBlockFn`) - Required - A function that returns a `boolean` or `Promise` to determine if navigation should be blocked. It receives `ShouldBlockFnArgs`. - **disabled** (`boolean`) - Optional (defaults to `false`) - Specifies if the blocker should be disabled. - **enableBeforeUnload** (`boolean | (() => boolean)`) - Optional (defaults to `true`) - Controls blocking of the browser `beforeUnload` event. - **withResolver** (`boolean`) - Optional (defaults to `false`) - If `true`, the hook returns controls to manually resolve blocking. - **blockerFn** (`BlockerFn`) - Optional (deprecated) - The function that returns a boolean or Promise indicating whether to allow navigation. - **condition** (`boolean`) - Optional (defaults to `true`) - A navigation attempt is blocked when this condition is `true`. ### Returns - An object with controls (`status`, `next`, `current`, `action`, `proceed`, `reset`) if `withResolver` is `true`. - `void` if `withResolver` is `false`. ### Examples #### Basic Usage ```tsx import { useBlocker } from '@tanstack/react-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = useState(false) useBlocker({ shouldBlockFn: () => formIsDirty, }) // ... } ``` #### Custom UI with Resolver ```tsx import { useBlocker } from '@tanstack/react-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = useState(false) const { proceed, reset, status, next } = useBlocker({ shouldBlockFn: () => formIsDirty, withResolver: true, }) // ... return ( <> {status === 'blocked' && (

You are navigating to {next.pathname}

Are you sure you want to leave?

)} ) } ``` #### Conditional Blocking with Resolver ```tsx import { useBlocker } from '@tanstack/react-router' function MyComponent() { const { proceed, reset, status } = useBlocker({ shouldBlockFn: ({ next }) => { return !next.pathname.includes('step/') }, withResolver: true, }) // ... return ( <> {status === 'blocked' && (

Are you sure you want to leave?

)} ) } ``` #### Without Resolver (using `confirm`) ```tsx import { useBlocker } from '@tanstack/react-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = useState(false) useBlocker({ shouldBlockFn: ({ next }) => { if (next.pathname.includes('step/')) { return false } const shouldLeave = confirm('Are you sure you want to leave?') return !shouldLeave }, }) // ... } ``` ``` -------------------------------- ### Load Route Matches (TypeScript) Source: https://tanstack.com/router/latest/docs/api/router/RouterType.md Loads all currently matched route data, resolving when all are ready. This is commonly used in SSR to ensure data is fetched before rendering. It respects `staleTime` and can be forced with `invalidate`. ```typescript type load = (opts?: {sync?: boolean}) => Promise ``` -------------------------------- ### Define a Virtual Pathless Route with a Pathless ID Source: https://tanstack.com/router/latest/docs/routing/virtual-file-routes.md Specify a pathless ID for a virtual pathless route using the `layout` function to provide a unique identifier different from the filename. Imports are required. ```typescript // routes.ts import { layout } from '@tanstack/virtual-file-routes' export const routes = rootRoute('root.tsx', [ layout('my-pathless-layout-id', 'pathlessLayout.tsx', [ // ... children routes ]), ]) ``` -------------------------------- ### JSX Route Definition (Not Recommended) Source: https://tanstack.com/router/latest/docs/decisions-on-dx.md Demonstrates a JSX-based route definition which is not supported by TanStack Router because TypeScript cannot infer route configuration types, leading to potential runtime errors. ```tsx function App() { return ( {/* ... */} // ^? TypeScript cannot infer the routes in this configuration ) } ``` -------------------------------- ### Router API Types Source: https://tanstack.com/router/latest/docs/api/router.md Reference the types and interfaces used within the TanStack Router for defining route structures and states. ```APIDOC ## Router API Types ### Description Defines the various types and interfaces used throughout the TanStack Router for data structures, options, and states. ### Types and Interfaces - **`ActiveLinkOptions Type`**: Options for active links. - **`AsyncRouteComponent Type`**: Type for asynchronous route components. - **`HistoryState Interface`**: Interface for history state. - **`LinkOptions Type`**: Options for link generation. - **`LinkProps Type`**: Props for the Link component. - **`MatchRouteOptions Type`**: Options for matching routes. - **`NavigateOptions Type`**: Options for navigation. - **`NotFoundError Type`**: Type for not found errors. - **`ParsedHistoryState Type`**: Type for parsed history state. - **`ParsedLocation Type`**: Type for parsed location. - **`Redirect Type`**: Type for redirect definitions. - **`Register Type`**: Type for route registration. - **`Route Type`**: Base type for routes. - **`RouteApi Type`**: Type for route API objects. - **`RouteMask Type`**: Type for route masks. - **`RouteMatch Type`**: Type for route match objects. - **`RouteOptions Type`**: Options for creating routes. - **`Router Type`**: Type for the router instance. - **`RouterEvents Type`**: Type for router events. - **`RouterOptions Type`**: Options for configuring the router. - **`RouterState Type`**: Type for the router's state. - **`ToMaskOptions Type`**: Options for converting to a mask. - **`ToOptions Type`**: Options for navigation targets. - **`UseMatchRouteOptions Type`**: Options for the `useMatchRoute` hook. - **`ViewTransitionOptions Type`**: Options for view transitions. ### Example Usage (Conceptual) ```typescript import type { RouteOptions, RouterOptions, RouteMatch } from '@tanstack/router' interface MyRouteOptions extends RouteOptions { // Custom route options } const routeConfig: MyRouteOptions = { path: '/users/:userId', // ... other options } const routerConfig: RouterOptions = { routes: [routeConfig], // ... other options } ``` ``` -------------------------------- ### VSCode Settings for Ignoring Generated Route Files Source: https://tanstack.com/router/latest/docs/installation/with-esbuild.md Configure VSCode settings to prevent linting, formatting, and searching of the generated routeTree.gen.ts file. This ensures the file is treated as read-only and excluded from relevant processes. ```json { "files.readonlyInclude": { "**/routeTree.gen.ts": true }, "files.watcherExclude": { "**/routeTree.gen.ts": true }, "search.exclude": { "**/routeTree.gen.ts": true } } ``` -------------------------------- ### Define an Index Route Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md Use a single slash '/' as the path to define an index route in code-based routing. ```tsx const postsRoute = createRoute({ getParentRoute: () => rootRoute, path: 'posts', }) const postsIndexRoute = createRoute({ getParentRoute: () => postsRoute, // Notice the single slash `/` here path: '/', }) ``` -------------------------------- ### Inject Custom Head Elements with head Source: https://tanstack.com/router/latest/docs/api/router/RouteOptionsType.md The `head` function enables the injection of custom elements into the document's `` for a specific route. It can return an object containing `links`, `scripts`, `meta`, and `styles`. This is ideal for route-level SEO, preloading resources, or adding inline styles and custom scripts. ```typescript type head = (ctx: { matches: Array match: RouteMatch params: TAllParams loaderData?: TLoaderData }) => | Promise<{ links?: RouteMatch['links'] scripts?: RouteMatch['headScripts'] meta?: RouteMatch['meta'] styles?: RouteMatch['styles'] }> | { links?: RouteMatch['links'] scripts?: RouteMatch['headScripts'] meta?: RouteMatch['meta'] styles?: RouteMatch['styles'] } ``` -------------------------------- ### loader Method Source: https://tanstack.com/router/latest/docs/api/router/RouteOptionsType.md The `loader` method is responsible for fetching data for a route. It's an asynchronous function that receives route match details and can return data or a promise for data. Errors thrown here put the route in an error state. The returned data is accessible via `useLoaderData`. ```APIDOC ## `loader` Method ### Description This async function fetches data for a route. It receives route match details and can return data or a promise. Errors result in an error state. Returned data is accessible via `useLoaderData`. ### Method `loader` ### Parameters - **opts** (object) - Required - Options object containing route match details, abort controller, cause, context, dependencies, location, params, preload status, parent match promise, navigation functions, and the route object. - **abortController** (AbortController) - An AbortController instance. - **cause** ('preload' | 'enter' | 'stay') - The reason for the loader call. - **context** (TAllContext) - All available context (parent + route). - **deps** (TLoaderDeps) - Dependencies returned by `loaderDeps`. - **location** (ParsedLocation) - The current parsed location. - **params** (TAllParams) - All route parameters. - **preload** (boolean) - Indicates if the route is being preloaded. - **parentMatchPromise** (Promise>) - A promise resolving to the parent route's match. - **navigate** (NavigateFn) - Deprecated: Function to navigate. - **route** (AnyRoute) - The current route object. ### Return Value - `Promise`: If a promise is returned, the route enters a pending state until it resolves. The resolved data is stored with the route match. - `TLoaderData`: Data to be stored with the route match. - `void`: If nothing is returned, the loader completes without providing data. ### Configuration Object - `handler` (loaderFn): The actual loader function. - `staleReloadMode` ('background' | 'blocking'): Configures how stale data is reloaded. 'background' allows stale-while-revalidate, 'blocking' waits for the reload. ### Error Handling - If an error is thrown, the route enters an error state and the error is thrown during render. - If thrown during navigation, the navigation is canceled and the error is passed to `onError`. - If thrown during preload, the error is logged, and preload fails. ### Example Usage ```typescript const route = new Route({ path: '/users/:userId', loader: async ({ params }) => { const response = await fetch(`/api/users/${params.userId}`); const data = await response.json(); return { user: data }; }, // ... other route configurations }); ``` > **Note**: The `opts.navigate` function is deprecated. Use `throw redirect({...})` for navigation. ``` -------------------------------- ### Default Split Groupings Configuration Source: https://tanstack.com/router/latest/docs/guide/automatic-code-splitting.md The default configuration for split groupings in TanStack Router. These groupings determine which route properties are bundled together into individual lazy-loaded chunks. ```shell [ ['component'], ['errorComponent'], ['notFoundComponent'] ] ``` -------------------------------- ### Offline-safe Redirects with TanStack Router Source: https://tanstack.com/router/latest/docs/guide/internationalization-i18n.md Implements offline-safe redirects using the `shouldRedirect` function from Paraglide's runtime within a `beforeLoad` hook. This handles potential redirect scenarios in client-only or offline environments. ```ts import { shouldRedirect } from '../paraglide/runtime' beforeLoad: async () => { const decision = await shouldRedirect({ url: window.location.href }) if (decision.redirectUrl) { throw redirect({ href: decision.redirectUrl.href }) } } ``` -------------------------------- ### getRouteApi().redirect usage outside route definitions Source: https://tanstack.com/router/latest/docs/api/router/redirectFunction.md Shows how to access and use the redirect functionality outside of route definition files using `getRouteApi`. This is useful for sharing redirect logic across different parts of an application while maintaining type safety and automatic 'from' parameter inference. ```tsx import { getRouteApi } from '@tanstack/react-router' const routeApi = getRouteApi('/dashboard/settings') // In a beforeLoad or loader callback function checkAuth() { if (!user) { // Type-safe redirect with automatic 'from' parameter throw routeApi.redirect({ to: '../login', }) } } ``` -------------------------------- ### Configure Allowed Path Parameters Source: https://tanstack.com/router/latest/docs/guide/path-params.md Allows specific characters in path parameters by configuring the `pathParamsAllowedCharacters` option in the router. This is useful for including characters like '@' or '+' that are not typically allowed in URIs. ```tsx const router = createRouter({ // ... pathParamsAllowedCharacters: ['@'], }) ``` -------------------------------- ### Update Search Params with useNavigate Hook Source: https://tanstack.com/router/latest/docs/guide/search-params.md The `useNavigate` hook accepts a `search` option, similar to the `` component's `search` prop. This allows programmatic navigation with updated search parameters. ```tsx export const Route = createFileRoute('/shop/products/$productId')({ validateSearch: productSearchSchema, }) const ProductList = () => { const navigate = useNavigate({ from: Route.fullPath }) return (
) } ``` -------------------------------- ### Define Route Matching Options - TypeScript Source: https://tanstack.com/router/latest/docs/api/router/MatchRouteOptionsType.md The MatchRouteOptions interface defines optional parameters for matching routes. These include matching pending locations, case sensitivity (deprecated), including search parameters, and fuzzy matching. ```typescript interface MatchRouteOptions { pending?: boolean caseSensitive?: boolean /* @deprecated */ includeSearch?: boolean fuzzy?: boolean } ``` -------------------------------- ### RouteApi - useParams Method Source: https://tanstack.com/router/latest/docs/api/router/RouteApiType.md Provides a type-safe version of the `useParams` hook, pre-bound to a specific route ID. ```APIDOC ## RouteApi - useParams Method ### Description A type-safe version of the `useParams` hook that is pre-bound to the route ID that the `RouteApi` instance was created with. ### Method `useParams(opts?: { select?: (params: TAllParams) => TSelected }): TSelected` ### Parameters #### Options - **opts.select** (function) - Optional - If supplied, this function will be called with the route match and the return value will be returned from `useParams`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks. - **opts.structuralSharing** (boolean) - Optional - Configures whether structural sharing is enabled for the value returned by `select`. See the [Render Optimizations guide](../../guide/render-optimizations.md) for more information. ### Returns - If a `select` function is provided, the return value of the `select` function. - If no `select` function is provided, the `TAllParams` object or a loosened version of the `TAllParams` object if `opts.strict` is `false`. ``` -------------------------------- ### Configure Link Active and Inactive States Source: https://tanstack.com/router/latest/docs/guide/navigation.md Use activeProps to apply styles or props when a link is active. Styles and classes are merged, while other props override defaults. ```tsx const link = ( Section 1 ) ``` -------------------------------- ### Enable Automatic Code Splitting in Vite Source: https://tanstack.com/router/latest/docs/guide/automatic-code-splitting.md Configure the TanStack Router plugin in your vite.config.ts file to enable automatic code splitting. This allows the router to optimize bundle size by lazily loading route components. ```typescript import { defineConfig } from 'vite' import { tanstackRouter } from '@tanstack/router-plugin/vite' export default defineConfig({ plugins: [ tanstackRouter({ autoCodeSplitting: true, // Enable automatic code splitting }), ], }) ``` -------------------------------- ### Access Router Instance with useRouter (React) Source: https://tanstack.com/router/latest/docs/api/router/useRouterHook.md The useRouter hook returns the current Router instance from context, enabling components to interact with the router. Note that router.state is not reactive; use useRouterState for reactive updates. ```tsx import { useRouter } from '@tanstack/react-router' function Component() { const router = useRouter() // ^ Router // ... } ``` -------------------------------- ### Accessing Route Context in Solid Source: https://tanstack.com/router/latest/docs/guide/data-loading.md Reference context defined in `createRootRouteWithContext` within your route loaders to access injected functions or data. This is useful for dependency injection. ```tsx // Notice how our postsRoute references context to get our fetchPosts function // This can be a powerful tool for dependency injection across your router // and routes. export const Route = createFileRoute('/posts')({ loader: ({ context: { fetchPosts } }) => fetchPosts(), }) ``` -------------------------------- ### NavigateOptions Type Definition Source: https://tanstack.com/router/latest/docs/api/router/NavigateOptionsType.md The NavigateOptions type defines the available options for customizing navigation actions within TanStack Router. ```APIDOC ## NavigateOptions Type ### Description The `NavigateOptions` type is used to describe the options that can be used when describing a navigation action in TanStack Router. ### Type Definition ```typescript type NavigateOptions = ToOptions & { replace?: boolean resetScroll?: boolean hashScrollIntoView?: boolean | ScrollIntoViewOptions viewTransition?: boolean | ViewTransitionOptions ignoreBlocker?: boolean reloadDocument?: boolean href?: string } ``` ### Properties #### `replace` - **Type**: `boolean` - **Optional** - **Defaults to**: `false` - **Description**: If `true`, the location will be committed to the browser history using `history.replace` instead of `history.push`. #### `resetScroll` - **Type**: `boolean` - **Optional** - **Defaults to**: `true` - **Description**: If `true`, the scroll position will be reset to 0,0 after the location is committed to the browser history. If `false`, the scroll position will not be reset. #### `hashScrollIntoView` - **Type**: `boolean | ScrollIntoViewOptions` - **Optional** - **Defaults to**: `true` - **Description**: If `true`, the element with an id matching the hash will be scrolled into view. If `false`, it will not. If an object is provided, it will be passed to the `scrollIntoView` method as options. #### `viewTransition` - **Type**: `boolean | ViewTransitionOptions` - **Optional** - **Defaults to**: `false` - **Description**: If `true`, navigation will use `document.startViewTransition()`. If an object is provided, it allows specifying `update` and `types` for view transitions. Ignored if the browser does not support view transitions. #### `ignoreBlocker` - **Type**: `boolean` - **Optional** - **Defaults to**: `false` - **Description**: If `true`, navigation will ignore any blockers that might prevent it. #### `reloadDocument` - **Type**: `boolean` - **Optional** - **Defaults to**: `false` - **Description**: If `true`, navigation will trigger a full page load instead of the traditional SPA navigation. #### `href` - **Type**: `string` - **Optional** - **Description**: Can be used instead of `to` to navigate to a fully built href, e.g. pointing to an external target. ``` -------------------------------- ### Generate Breadcrumbs from Context Source: https://tanstack.com/router/latest/docs/guide/router-context.md Access matched route contexts via useRouterState to build dynamic UI elements like breadcrumbs. ```tsx export const Route = createRootRoute({ component: () => { const matches = useRouterState({ select: (s) => s.matches }) const breadcrumbs = matches .filter((match) => match.context.getTitle) .map(({ pathname, context }) => { return { title: context.getTitle(), path: pathname, } }) // ... }, }) ``` -------------------------------- ### Create Mantine Anchor Integration Source: https://tanstack.com/router/latest/docs/guide/custom-link.md Wraps a Mantine Anchor component with createLink to enable router navigation while maintaining Mantine's styling and prop interface. ```tsx import * as React from 'react' import { createLink, LinkComponent } from '@tanstack/react-router' import { Anchor, AnchorProps } from '@mantine/core' interface MantineAnchorProps extends Omit {} const MantineLinkComponent = React.forwardRef( (props, ref) => { return } ) const CreatedLinkComponent = createLink(MantineLinkComponent) export const CustomLink: LinkComponent = ( props, ) => { return } ``` -------------------------------- ### loaderDeps Method Source: https://tanstack.com/router/latest/docs/api/router/RouteOptionsType.md The `loaderDeps` method is called before a route is matched to provide unique identification for the route match and track dependencies for reloading. It should return serializable values, typically search parameters, to ensure correct data fetching. ```APIDOC ## `loaderDeps` Method ### Description This function is called before a route is matched to provide unique identification for the route match and track dependencies for reloading. It should return serializable values, often search parameters, to ensure accurate data fetching. ### Method `loaderDeps` ### Parameters - **opts** (object) - Required - Options object containing search parameters. - **search** (TFullSearchSchema) - The search schema for the route. ### Return Value - `Record`: An object containing serializable values that uniquely identify the route match and serve as dependencies for reloading. Path parameters are automatically included. ### Example Usage ```typescript const route = new Route({ path: '/products', loaderDeps: ({ search }) => { // Return search params to ensure loader reloads when they change return { category: search.category }; }, loader: async ({ deps }) => { const response = await fetch(`/api/products?category=${deps.category}`); const data = await response.json(); return { products: data }; }, // ... other route configurations }); ``` ``` -------------------------------- ### Narrow LinkProps for better performance Source: https://tanstack.com/router/latest/docs/guide/type-safety.md Narrowing LinkProps with specific route information significantly improves type checking speed. ```tsx const props = { to: '/posts/', } as const satisfies LinkProps return ( ) ``` -------------------------------- ### Define Search Params with Effect/Schema Source: https://tanstack.com/router/latest/docs/guide/search-params.md Uses Effect/Schema to define search parameters for a route, leveraging Standard Schema for automatic type inference. ```tsx import { Schema as S } from 'effect' const productSearchSchema = S.standardSchemaV1( S.Struct({ page: S.NumberFromString.pipe( S.optional, S.withDefaults({ constructor: () => 1, decoding: () => 1, }), ), filter: S.String.pipe( S.optional, S.withDefaults({ constructor: () => '', decoding: () => '', }), ), sort: S.Literal('newest', 'oldest', 'price').pipe( S.optional, S.withDefaults({ constructor: () => 'newest' as const, decoding: () => 'newest' as const, }), ), }), ) export const Route = createFileRoute('/shop/products/')({ validateSearch: productSearchSchema, }) ``` -------------------------------- ### Define Route with Context Loader Source: https://tanstack.com/router/latest/docs/guide/router-context.md Accesses context within a route definition to perform data fetching. ```tsx // src/routes/todos.tsx export const Route = createFileRoute('/todos')({ component: Todos, loader: ({ context }) => fetchTodosByUserId(context.user.id), }) ``` -------------------------------- ### React Route Definition with Optional Locale Parameter Source: https://tanstack.com/router/latest/docs/guide/path-params.md Defines a route with an optional locale parameter '/{-$locale}/'. This allows for flexible URL structures like '/', '/en', or '/fr'. It also demonstrates accessing route parameters and conditionally setting the 'dir' attribute based on locale. ```tsx // Route structure: // routes/ // -{$locale}/ // index.tsx // /, /en, /fr // about.tsx // /about, /en/about, /fr/about // blog/ // index.tsx // /blog, /en/blog, /fr/blog // $slug.tsx // /blog/post, /en/blog/post, /fr/blog/post // routes/{-$locale}/index.tsx export const Route = createFileRoute('/{-$locale}/')({ component: HomeComponent, }) function HomeComponent() { const { locale } = Route.useParams() const isRTL = ['ar', 'he', 'fa'].includes(locale || '') return (

Welcome ({locale || 'en'})

{/* Localized content */}
) } // routes/{-$locale}/about.tsx export const Route = createFileRoute('/{-$locale}/about')({ component: AboutComponent, }) ``` -------------------------------- ### Update Search Params in Specific Subtree with Link Source: https://tanstack.com/router/latest/docs/guide/search-params.md For generic components within a specific route subtree, specify the subtree using the `from` prop on the `` component. The `to='.'` prop can be omitted in this case. ```tsx // `page` is a search param that is defined in the /posts route and hence available on all of its child routes. const PageSelector = () => { return (
({ ...prev, page: prev.page + 1 })} > Next Page
) } ``` -------------------------------- ### codeSplitGroupings Property Source: https://tanstack.com/router/latest/docs/api/router/RouteOptionsType.md Configures how lazy-loaded assets are grouped into chunks. ```APIDOC ## codeSplitGroupings ### Description Provides fine-grained control over how the router groups lazy-loaded pieces of a route into chunks. ### Type Array> ``` -------------------------------- ### Create Link with JSON Search Params Source: https://tanstack.com/router/latest/docs/guide/search-params.md Use the `search` object in the `Link` component to pass structured JSON data as URL search parameters. Nested data structures are automatically converted to URL-safe JSON strings. ```tsx const link = ( ) ``` -------------------------------- ### Create Permission Guard Component Source: https://tanstack.com/router/latest/docs/how-to/setup-rbac.md A reusable component that conditionally renders its children based on user roles and permissions. It accepts optional roles, permissions, and a fallback UI. ```tsx interface PermissionGuardProps { children: React.ReactNode roles?: string[] permissions?: string[] requireAll?: boolean fallback?: React.ReactNode } export function PermissionGuard({ children, roles = [], permissions = [], requireAll = false, fallback = null, }: PermissionGuardProps) { const { hasAnyRole, hasAnyPermission, hasRole, hasPermission } = usePermissions() const hasRequiredRoles = roles.length === 0 || (requireAll ? roles.every((role) => hasRole(role)) : hasAnyRole(roles)) const hasRequiredPermissions = permissions.length === 0 || (requireAll ? permissions.every((permission) => hasPermission(permission)) : hasAnyPermission(permissions)) if (hasRequiredRoles && hasRequiredPermissions) { return <>{children} } return <>{fallback} } ``` -------------------------------- ### Embed Devtools Panel in Solid App Source: https://tanstack.com/router/latest/docs/devtools.md Embeds the TanStack Router Devtools Panel as a standard component in a SolidJS application. This provides flexibility for styling and placement within the application's structure. ```tsx import { TanStackRouterDevtoolsPanel } from '@tanstack/solid-router-devtools' function App() { return ( <> ) } ``` -------------------------------- ### TanStack Router: loader Method Source: https://tanstack.com/router/latest/docs/api/router/RouteOptionsType.md The loader method is an optional async function called when a route is matched to fetch data. It supports returning promises for pending states and TLoaderData for accessible data. Errors thrown are handled during rendering or navigation. It can be configured with staleReloadMode for caching strategies. ```typescript type loaderFn = ( opts: RouteMatch & { abortController: AbortController cause: 'preload' | 'enter' | 'stay' context: TAllContext deps: TLoaderDeps location: ParsedLocation params: TAllParams preload: boolean parentMatchPromise: Promise> navigate: NavigateFn // @deprecated route: AnyRoute }, ) => Promise | TLoaderData | void type loader = | loaderFn | { handler: loaderFn staleReloadMode?: 'background' | 'blocking' } ``` -------------------------------- ### Update Router Context Types for Authentication Source: https://tanstack.com/router/latest/docs/how-to/setup-rbac.md Define the `MyRouterContext` interface to include the `AuthState` from your authentication context. This makes authentication state available throughout your router. ```tsx import { createRootRouteWithContext, Outlet } from '@tanstack/react-router' interface AuthState { isAuthenticated: boolean user: { id: string username: string email: string roles: string[] permissions: string[] } | null hasRole: (role: string) => boolean hasAnyRole: (roles: string[]) => boolean hasPermission: (permission: string) => boolean hasAnyPermission: (permissions: string[]) => boolean login: (username: string, password: string) => Promise logout: () => void } interface MyRouterContext { auth: AuthState } export const Route = createRootRouteWithContext()({ component: () => (
), }) ``` -------------------------------- ### Define a Layout Route Component Source: https://tanstack.com/router/latest/docs/routing/routing-concepts.md Use the Outlet component to render child routes within a layout wrapper. ```tsx import { Outlet, createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/app')({ component: AppLayoutComponent, }) function AppLayoutComponent() { return (

App Layout

) } ``` ```tsx import { Outlet, createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/app')({ component: AppLayoutComponent, }) function AppLayoutComponent() { return (

App Layout

) } ``` -------------------------------- ### Code Splitting and Type Generation Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md Control automatic code splitting and type generation for the route tree. ```APIDOC ### `autoCodeSplitting` This feature is only available if you are using the TanStack Router Bundler Plugin. This option is used to enable automatic code-splitting for non-critical route configuration items. See the "Automatic Code-Splitting" guide for more information. By default, this value is set to `false`. > [!IMPORTANT] > The next major release of TanStack Router (i.e. v2), will have this value defaulted to `true`. ### `disableTypes` This option is used to disable generating types for the route tree. If set to `true`, the generated route tree will not include any types and will be written as a `.js` file instead of a `.ts` file. ``` -------------------------------- ### RouteApi - useSearch Method Source: https://tanstack.com/router/latest/docs/api/router/RouteApiType.md Provides a type-safe version of the `useSearch` hook, pre-bound to a specific route ID. ```APIDOC ## RouteApi - useSearch Method ### Description A type-safe version of the `useSearch` hook that is pre-bound to the route ID that the `RouteApi` instance was created with. ### Method `useSearch(opts?: { select?: (search: TFullSearchSchema) => TSelected }): TSelected` ### Parameters #### Options - **opts.select** (function) - Optional - If supplied, this function will be called with the route match and the return value will be returned from `useSearch`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks. - **opts.structuralSharing** (boolean) - Optional - Configures whether structural sharing is enabled for the value returned by `select`. See the [Render Optimizations guide](../../guide/render-optimizations.md) for more information. ### Returns - If a `select` function is provided, the return value of the `select` function. - If no `select` function is provided, the `TFullSearchSchema` object or a loosened version of the `TFullSearchSchema` object if `opts.strict` is `false`. ``` -------------------------------- ### Server-side Considerations: SSR Hydration Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md Covers how TanStack Router ensures consistent URLs between server-rendered HTML and client hydration, including the serialization of `publicHref`. ```APIDOC ### SSR Hydration The router ensures that the server-rendered HTML and client hydration use consistent URLs. The `publicHref` is serialized during SSR so the client can hydrate with the correct external URL. ``` -------------------------------- ### isNotFound Utility Function Source: https://tanstack.com/router/latest/docs/api/router/isNotFoundFunction.md A utility function to determine if an object is a NotFoundError, useful for error handling in routing logic. ```APIDOC ## isNotFound(input) ### Description The `isNotFound` function is a type-guard that checks if a provided object is an instance of a `NotFoundError`. It is commonly used within catch blocks or error handling logic to determine if a navigation or data loading failure was caused by a missing route or resource. ### Parameters #### Arguments - **input** (unknown) - Required - The object to evaluate. ### Returns - **boolean** - Returns `true` if the input is a `NotFoundError`, otherwise `false`. ### Usage Example ```tsx import { isNotFound } from '@tanstack/react-router'; function handleRouteError(error: unknown) { if (isNotFound(error)) { console.log('The requested route was not found.'); } } ``` ``` -------------------------------- ### Manually Passing Router Instance Source: https://tanstack.com/router/latest/docs/devtools.md Pass the router instance explicitly to the devtools component if you need to render them outside of the standard RouterProvider context. ```tsx function App() { return ( <> ); } ``` ```tsx function App() { return ( <> ); } ``` -------------------------------- ### Implement Component-based Navigation Blocking Source: https://tanstack.com/router/latest/docs/guide/navigation-blocking.md Uses the Block component to conditionally block navigation. Supports both simple boolean logic and resolver-based custom UI rendering. ```tsx import { Block } from '@tanstack/solid-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = useState(false) return ( { if (!formIsDirty) return false const shouldLeave = confirm('Are you sure you want to leave?') return !shouldLeave }} enableBeforeUnload={formIsDirty} /> ) } ``` ```tsx import { Block } from '@tanstack/solid-router' function MyComponent() { const [formIsDirty, setFormIsDirty] = createSignal(false) return ( { if (!formIsDirty()) return false const shouldLeave = confirm('Are you sure you want to leave?') return !shouldLeave }} /> ) } ``` -------------------------------- ### Create Language Switcher Component Source: https://tanstack.com/router/latest/docs/guide/path-params.md Uses the Link component with functional params to update locale while preserving other route parameters. ```tsx function LanguageSwitcher() { const currentParams = useParams({ strict: false }) const languages = [ { code: 'en', name: 'English' }, { code: 'fr', name: 'Français' }, { code: 'es', name: 'Español' }, ] return (
{languages.map(({ code, name }) => ( ({ ...prev, locale: code === 'en' ? undefined : code, // Remove 'en' for clean URLs })} className={currentParams.locale === code ? 'active' : ''} > {name} ))}
) } ``` -------------------------------- ### Define an index route Source: https://tanstack.com/router/latest/docs/routing/routing-concepts.md Index routes target a parent path when no child route is matched. Use a trailing slash in the path string to define them. ```tsx import { createFileRoute } from '@tanstack/react-router' // Note the trailing slash, which is used to target index routes export const Route = createFileRoute('/posts/')({ component: PostsIndexComponent, }) function PostsIndexComponent() { return
Please select a post!
} ``` ```tsx import { createFileRoute } from '@tanstack/solid-router' // Note the trailing slash, which is used to target index routes export const Route = createFileRoute('/posts/')({ component: PostsIndexComponent, }) function PostsIndexComponent() { return
Please select a post!
} ``` -------------------------------- ### Invert control with render props Source: https://tanstack.com/router/latest/docs/guide/type-safety.md Use render props to pass a narrowed Link component, avoiding the need to use LinkProps entirely. ```tsx export interface MyComponentProps { readonly renderLink: () => React.ReactNode } const MyComponent = (props: MyComponentProps) => { return
{props.renderLink()}
} const Page = () => { return } /> } ``` -------------------------------- ### Migrate to notFoundComponent Source: https://tanstack.com/router/latest/docs/guide/not-found-errors.md Migrate from the deprecated `NotFoundRoute` API to `notFoundComponent`. This involves adding `notFoundComponent` to the root route or specific routes and removing the old `notFoundRoute` configuration. ```tsx import { createRouter } from '@tanstack/react-router' import { routeTree } from './routeTree.gen.' - import { notFoundRoute } from './notFoundRoute' // [!code --] export const router = createRouter({ routeTree, - notFoundRoute // [!code --] }) ``` ```tsx // routes/__root.tsx import { createRootRoute } from '@tanstack/react-router' export const Route = createRootRoute({ // ... + notFoundComponent: () => { // [!code ++] + return

Not found!

// [!code ++] + } // [!code ++] }) ``` -------------------------------- ### Access Splat Route Parameters Source: https://tanstack.com/router/latest/docs/routing/routing-concepts.md Splat routes using '$' capture remaining URL segments into the '_splat' property of the params object. ```js { '_splat': 'documents/hello-world' } ``` -------------------------------- ### Use `useSearch` with `strict: false` Source: https://tanstack.com/router/latest/docs/guide/type-safety.md When using hooks like `useSearch` in shared components or when the route context is unknown, pass `strict: false` to avoid runtime errors and receive a union of all possible search param types across all routes. ```tsx function MyComponent() { const search = useSearch({ strict: false }) } ``` -------------------------------- ### Link Component Active Options Interface Source: https://tanstack.com/router/latest/docs/guide/navigation.md Defines the available options for customizing how the Link component determines if it is active. Defaults are provided for most options. ```typescript export interface ActiveOptions { // If true, the link will be active if the current route matches the `to` route path exactly (no children routes) // Defaults to `false` exact?: boolean // If true, the link will only be active if the current URL hash matches the `hash` prop // Defaults to `false` includeHash?: boolean // Defaults to false // If true, the link will only be active if the current URL search params inclusively match the `search` prop // Defaults to `true` includeSearch?: boolean // This modifies the `includeSearch` behavior. // If true, properties in `search` that are explicitly `undefined` must NOT be present in the current URL search params for the link to be active. // defaults to `false` explicitUndefined?: boolean } ``` -------------------------------- ### Use Type-Safe Route Hooks Source: https://tanstack.com/router/latest/docs/guide/type-safety.md Access type-safe versions of hooks like `useParams` and `useSearch` directly from the route object. For hooks requiring router-wide context, such as `useNavigate`, pass the `from` parameter with the route's `fullPath` to maintain type safety. ```tsx export const Route = createFileRoute('/posts')({ component: PostsComponent, }) function PostsComponent() { // Each route has type-safe versions of most of the built-in hooks from TanStack Router const params = Route.useParams() const search = Route.useSearch() // Some hooks require context from the *entire* router, not just the current route. To achieve type-safety here, // we must pass the `from` param to tell the hook our relative position in the route hierarchy. const navigate = useNavigate({ from: Route.fullPath }) // ... etc } ``` -------------------------------- ### Implement error retry with reset Source: https://tanstack.com/router/latest/docs/guide/data-loading.md Uses the reset function to clear the error boundary and attempt to re-render the route. ```tsx // src/routes/posts.tsx export const Route = createFileRoute('/posts')({ loader: () => fetchPosts(), errorComponent: ({ error, reset }) => { return (
{error.message}
) }, }) ``` -------------------------------- ### Conditional Data Loading with Preload Flag Source: https://tanstack.com/router/latest/docs/guide/data-loading.md Use the `preload` flag in the loader to conditionally adjust data fetching logic, such as cache duration, when a route is being preloaded versus actively loaded. This allows for optimized preloading strategies. ```tsx export const Route = createFileRoute('/posts')({ loader: async ({ preload }) => fetchPosts({ maxAge: preload ? 10_000 : 0, // Preloads should hang around a bit longer }), }) ``` -------------------------------- ### Implement Programmatic Split Behavior Source: https://tanstack.com/router/latest/docs/guide/automatic-code-splitting.md Define custom logic for route chunking based on routeId using the splitBehavior function in your bundler configuration. This is useful for complex applications requiring dynamic grouping. ```ts splitBehavior: ({ routeId }) => { if (routeId.startsWith('/posts')) { return [['loader', 'component']] } }, ``` -------------------------------- ### Define View Transition Types with ViewTransitionOptions (TypeScript) Source: https://tanstack.com/router/latest/docs/api/router/ViewTransitionOptionsType.md The ViewTransitionOptions type defines how view transitions are handled. The 'types' property can be a static array of strings or a dynamic function that returns an array of strings or false to skip transitions, based on location change details. ```typescript interface ViewTransitionOptions { types: | Array | ((locationChangeInfo: { fromLocation?: ParsedLocation toLocation: ParsedLocation pathChanged: boolean hrefChanged: boolean hashChanged: boolean }) => Array | false) } ``` -------------------------------- ### Accessing Event Payload (TypeScript/React) Source: https://tanstack.com/router/latest/docs/guide/router-events.md Shows how to access event payload data within a 'onBeforeNavigate' subscription. It logs information about the navigation, including source and destination locations, and whether path, href, or hash have changed. ```tsx const unsubscribe = router.subscribe('onBeforeNavigate', (event) => { console.info({ from: event.fromLocation?.href, to: event.toLocation.href, pathChanged: event.pathChanged, hrefChanged: event.hrefChanged, hashChanged: event.hashChanged, }) }) ``` -------------------------------- ### useRouteContext Hook Source: https://tanstack.com/router/latest/docs/api/router/useRouteContextHook.md Access the current route context or a selected portion of it using the useRouteContext hook. ```APIDOC ## useRouteContext Hook ### Description The `useRouteContext` hook returns the current context for a specified route. It is primarily used within React components to access data provided by route loaders or context providers. ### Parameters #### Options Object - **from** (string) - Required - The RouteID to match the route context from. - **select** (function) - Optional - A selector function `(context: RouteContext) => TSelected` to extract specific data from the context. ### Returns - Returns the full route context object, or the value returned by the `select` function if provided. ### Usage Example ```tsx import { useRouteContext } from '@tanstack/react-router' function Component() { // Access full context const context = useRouteContext({ from: '/posts/$postId' }) // Access selected data const selected = useRouteContext({ from: '/posts/$postId', select: (context) => context.postId, }) } ``` ``` -------------------------------- ### Avoid Exporting Route Components Source: https://tanstack.com/router/latest/docs/guide/automatic-code-splitting.md To ensure proper code splitting, do not export route-specific components like notFoundComponent. Keep them scoped within the file to prevent them from being bundled into the main application bundle. ```tsx export const Route = createRoute('/posts')({ notFoundComponent: PostsNotFoundComponent, }) function PostsNotFoundComponent() { // ✅ Correct: Not exported } ``` -------------------------------- ### Load Route Chunk API Source: https://tanstack.com/router/latest/docs/api/router/RouterType.md Loads the JavaScript chunk for a specific route. ```APIDOC ## loadRouteChunk Method ### Description Loads the JS chunk of the route. ### Method `loadRouteChunk` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **route** (AnyRoute) - Required - The route whose JS chunk needs to be loaded. ### Request Example ```json { "path": "/users/:id", "component": "() => import('./Users')" } ``` ### Response #### Success Response (200) This method returns a Promise that resolves when the route chunk is loaded. #### Response Example ```json null ``` ``` -------------------------------- ### Non-Redirected Authentication with TanStack Router Source: https://tanstack.com/router/latest/docs/guide/authenticated-routes.md This snippet shows how to implement authentication without redirecting the user to a separate login page. It conditionally renders a login form or the child routes based on the authentication status, keeping the user on the current page. ```tsx import { createFileRoute, Outlet } from '@tanstack/react-router'; // Assume isAuthenticated() is a function that returns a boolean // Assume Login is a React component for the login form export const Route = createFileRoute('/_authenticated')({ component: () => { if (!isAuthenticated()) { return } return }, }); ``` -------------------------------- ### Configure Scroll Restoration Behavior (Router) Source: https://tanstack.com/router/latest/docs/guide/scroll-restoration.md Configures the scroll behavior during page navigation. The `scrollRestorationBehavior` option accepts 'smooth', 'instant', or 'auto', similar to browser's `scrollIntoView` behavior. This setting affects the transition between pages. ```tsx const router = createRouter({ scrollRestorationBehavior: 'instant', }) ``` -------------------------------- ### Chain multiple search middlewares Source: https://tanstack.com/router/latest/docs/guide/search-params.md Combines both retainSearchParams and stripSearchParams within a single route configuration. ```tsx import { Link, createFileRoute, retainSearchParams, stripSearchParams, } from '@tanstack/react-router' import { z } from 'zod' import { zodValidator } from '@tanstack/zod-adapter' const defaultValues = ['foo', 'bar'] export const Route = createFileRoute('/search')({ validateSearch: zodValidator( z.object({ retainMe: z.string().optional(), arrayWithDefaults: z.string().array().default(defaultValues), required: z.string(), }), ), search: { middlewares: [ retainSearchParams(['retainMe']), stripSearchParams({ arrayWithDefaults: defaultValues }), ], }, }) ``` ```tsx import { Link, createFileRoute, retainSearchParams, stripSearchParams, } from '@tanstack/solid-router' import { z } from 'zod' import { zodValidator } from '@tanstack/zod-adapter' const defaultValues = ['foo', 'bar'] export const Route = createFileRoute('/search')({ validateSearch: zodValidator( z.object({ retainMe: z.string().optional(), arrayWithDefaults: z.string().array().default(defaultValues), required: z.string(), }), ), search: { middlewares: [ retainSearchParams(['retainMe']), stripSearchParams({ arrayWithDefaults: defaultValues }), ], }, }) ``` -------------------------------- ### Update Search Params with Link Component Source: https://tanstack.com/router/latest/docs/guide/search-params.md Use the `search` prop on the `` component to update search parameters for the current page. The `from` prop specifies the current route, and the `search` prop accepts a function that receives previous search params and returns new ones. ```tsx export const Route = createFileRoute('/shop/products')({ validateSearch: productSearchSchema, }) const ProductList = () => { return (
({ page: prev.page + 1 })}> Next Page
) } ``` -------------------------------- ### Checking for route existence without throwing Source: https://tanstack.com/router/latest/docs/api/router/useMatchHook.md Illustrates how to check if a specific route is currently rendered by setting shouldThrow to false. This returns undefined if the match is not found instead of throwing an error. ```tsx import { useMatch } from '@tanstack/react-router' function Component() { const match = useMatch({ from: '/posts', shouldThrow: false }) if (match !== undefined) { // Handle match presence } } ``` -------------------------------- ### Attach Devtools Panel to Shadow DOM (React) Source: https://tanstack.com/router/latest/docs/devtools.md Attaches the TanStack Router Devtools Panel to a specified Shadow DOM target in a React application. This allows for isolated styling and rendering of the devtools. ```tsx ``` -------------------------------- ### Link Component with Active State Children Function Source: https://tanstack.com/router/latest/docs/guide/navigation.md Shows how to use a function as a child of the Link component to access and utilize the `isActive` state for conditional styling or rendering. ```tsx const link = ( {({ isActive }) => { return ( <> My Blog Post ) }} ) ```