### Install Dependencies and Run Development Server Source: https://tanstack.com/router/v1/docs/framework/solid/examples/authenticated-routes Use this command to install project dependencies and start the development server for the TanStack Solid Router example. ```bash npm install && npm run dev ``` -------------------------------- ### Install Project Dependencies Source: https://tanstack.com/router/v1/docs/framework/solid/examples/navigation-blocking Use npm or yarn to install the required packages for the project. ```bash npm install ``` ```bash yarn ``` -------------------------------- ### Install Auth0 SDK Source: https://tanstack.com/router/v1/docs/how-to/setup-auth-providers.md Install the Auth0 React SDK using npm. ```bash npm install @auth0/auth0-react ``` -------------------------------- ### FileRoute Example Source: https://tanstack.com/router/v1/docs/api/router/FileRouteClass.md Example demonstrating how to use the deprecated `FileRoute` class to create a route with a loader and component. ```APIDOC ### Examples ```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
{data}
} ``` ``` -------------------------------- ### Solid.js TanStack Router Deferred Data Application Setup Source: https://tanstack.com/router/v1/docs/framework/solid/examples/deferred-data This comprehensive example demonstrates setting up a Solid.js application with TanStack Router to handle deferred data loading. It includes route definitions, data fetching with `defer`, and component rendering with `Suspense` and `Await` for a complete application flow. ```typescript import { render } from 'solid-js/web' import { Suspense } from 'solid-js' import { Await, ErrorComponent, Link, MatchRoute, Outlet, RouterProvider, createRootRoute, createRoute, createRouter, defer, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import axios from 'redaxios' import type { ErrorComponentProps } from '@tanstack/solid-router' import './styles.css' type PostType = { id: string title: string body: string } type CommentType = { id: string postId: string name: string email: string body: string } const fetchPosts = async () => { console.info('Fetching posts...') await new Promise((r) => setTimeout(r, 100)) return axios .get>('https://jsonplaceholder.typicode.com/posts') .then((r) => r.data.slice(0, 10)) } const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) const commentsPromise = new Promise((r) => setTimeout(r, 2000)) .then(() => axios.get>( `https://jsonplaceholder.typicode.com/comments?postId=${postId}`, ), ) .then((r) => r.data) const post = await new Promise((r) => setTimeout(r, 1000)) .then(() => axios.get( `https://jsonplaceholder.typicode.com/posts/${postId}`, ), ) .catch((err) => { if (err.status === 404) { throw new NotFoundError(`Post with id "${postId}" not found!`) } throw err }) .then((r) => r.data) return { post, commentsPromise: defer(commentsPromise), } } function Spinner({ show, wait }: { show?: boolean; wait?: `delay-${number}` }) { return (
) } const rootRoute = createRootRoute({ component: RootComponent, }) function RootComponent() { return ( <>
Home {' '} Posts

{/* Start rendering router matches */} ) } const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', }).update({ component: IndexComponent, }) function IndexComponent() { return (

Welcome Home!

) } const postsRoute = createRoute({ getParentRoute: () => rootRoute, path: 'posts', loader: fetchPosts, component: PostsComponent, }) function PostsComponent() { const posts = postsRoute.useLoaderData() ``` -------------------------------- ### Install Clerk SDK Source: https://tanstack.com/router/v1/docs/how-to/setup-auth-providers.md Install the Clerk React SDK using npm. ```bash npm install @clerk/clerk-react ``` -------------------------------- ### Start Development Server Source: https://tanstack.com/router/v1/docs/framework/solid/examples/navigation-blocking Run the project's development server using npm or yarn. ```bash npm start ``` ```bash yarn start ``` -------------------------------- ### Solid Project Dependencies Source: https://tanstack.com/router/v1/docs/quick-start.md Example of how TanStack Router appears in a Solid project's package.json file after installation. ```json { "dependencies": { "@tanstack/solid-router": "^x.x.x" } } ``` -------------------------------- ### Basic Usage Example Source: https://tanstack.com/router/v1/docs/api/router/useBlockerHook.md A simple example demonstrating how to use the `useBlocker` hook to block navigation when a form is dirty. ```APIDOC ## Basic Usage ### Description This example shows how to block navigation when a form's state indicates it has unsaved changes. ### Code ```tsx import { useBlocker } from '@tanstack/react-router' import { useState } from 'react' function MyComponent() { const [formIsDirty, setFormIsDirty] = useState(false) useBlocker({ shouldBlockFn: () => formIsDirty, }) // ... other component logic return (
{/* Form elements that can change formIsDirty state */}
) } ``` ``` -------------------------------- ### Solid Router Setup with QueryClient Context Source: https://tanstack.com/router/v1/docs/guide/router-context.md Set up a Solid router with a root route that includes a QueryClient in its context. ```tsx import { createRootRouteWithContext, createRouter, } from '@tanstack/solid-router' interface MyRouterContext { queryClient: QueryClient } const rootRoute = createRootRouteWithContext()({ component: App, }) const queryClient = new QueryClient() const router = createRouter({ routeTree: rootRoute, context: { queryClient, }, }) ``` -------------------------------- ### Placeholder for Solid.js Link Example Source: https://tanstack.com/router/v1/docs/guide/custom-link.md This is a placeholder for a Solid.js example. The TODO comment indicates that this example is not yet implemented. ```tsx // TODO: Add this example. ``` -------------------------------- ### Install Supabase Client Source: https://tanstack.com/router/v1/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 ``` -------------------------------- ### Route Class Example Source: https://tanstack.com/router/v1/docs/api/router/RouteClass.md Example demonstrating how to create a route instance using the deprecated Route class. ```APIDOC ## Examples ```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
{data}
} ``` ``` -------------------------------- ### Scaffold New TanStack Router Project (Solid) Source: https://tanstack.com/router/v1/docs/quick-start.md Use the TanStack CLI to create a new project with router-only setup for Solid. The CLI will guide you through customization options. ```bash @tanstack/cli create --router-only --framework solid ``` -------------------------------- ### Event Subscription Example Source: https://tanstack.com/router/v1/docs/api/router/RouterEventsType.md An example demonstrating how to subscribe to router events, specifically the 'onResolved' event, and receive event payloads. ```APIDOC ## Example Usage This example shows how to create a router and subscribe to the `onResolved` event. ### Code Example ```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 payload console.log('Route resolved:', evt.toLocation) }) // To unsubscribe later: // unsub() ``` ``` -------------------------------- ### Solid Router and Solid Query Application Setup Source: https://tanstack.com/router/v1/docs/framework/solid/examples/basic-solid-query This snippet demonstrates the foundational setup for a Solid application integrating TanStack Router and TanStack Solid Query, including root route configuration, main application component, and basic route definitions. ```typescript import { ErrorComponent, HeadContent, Link, Outlet, RouterProvider, createRootRouteWithContext, createRoute, createRouter, useRouter, } from '@tanstack/solid-router' import { QueryClient, QueryClientProvider, useQuery, } from '@tanstack/solid-query' import './styles.css' import { render } from 'solid-js/web' import { SolidQueryDevtools } from '@tanstack/solid-query-devtools' import { createEffect, createMemo } from 'solid-js' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import { NotFoundError, postQueryOptions, postsQueryOptions } from './posts' import type { ErrorComponentProps } from '@tanstack/solid-router' const rootRoute = createRootRouteWithContext<{ queryClient: QueryClient }>()({ component: RootComponent, notFoundComponent: () => { return (

This is the notFoundComponent configured on root route

Start Over
) }, }) function RootComponent() { return ( <>
Home {' '} Posts {' '} Pathless Layout {' '} This Route Does Not Exist

) } const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', component: IndexRouteComponent, }) function IndexRouteComponent() { return (

Welcome Home!

) } const postsLayoutRoute = createRoute({ getParentRoute: () => rootRoute, path: 'posts', loader: ({ context: { queryClient } }) => queryClient.ensureQueryData(postsQueryOptions), }).lazy(() => import('./posts.lazy').then((d) => d.Route)) const postsIndexRoute = createRoute({ getParentRoute: () => postsLayoutRoute, path: '/', component: PostsIndexRouteComponent, }) function PostsIndexRouteComponent() { return
Select a post.
} const postRoute = createRoute({ getParentRoute: () => postsLayoutRoute, path: '$postId', errorComponent: PostErrorComponent, loader: ({ context: { queryClient }, params: { postId } }) => queryClient.ensureQueryData(postQueryOptions(postId)), component: PostRouteComponent, }) function PostErrorComponent({ error, reset }: ErrorComponentProps) { const router = useRouter() if (error instanceof NotFoundError) { return
{error.message}
} createEffect(() => { reset() queryClient.resetQueries() }) ``` -------------------------------- ### Install TanStack Router CLI Source: https://tanstack.com/router/v1/docs/installation/with-router-cli.md Install the CLI as a dev dependency for your project. ```bash react: @tanstack/router-cli solid: @tanstack/router-cli ``` -------------------------------- ### Custom UI with Resolver Example Source: https://tanstack.com/router/v1/docs/api/router/useBlockerHook.md Demonstrates how to use `useBlocker` with `withResolver: true` to present a custom confirmation UI to the user. ```APIDOC ## Custom UI with Resolver ### Description This example utilizes the `withResolver: true` option to display a custom modal or dialog for navigation confirmation. ### Code ```tsx import { useBlocker } from '@tanstack/react-router' import { useState } from 'react' function MyComponent() { const [formIsDirty, setFormIsDirty] = useState(false) const { proceed, reset, status, next } = useBlocker({ shouldBlockFn: () => formIsDirty, withResolver: true, }) // ... other component logic return (
{/* Form elements */} {status === 'blocked' && (

You are navigating to {next.pathname}

Are you sure you want to leave?

)}
) } ``` ``` -------------------------------- ### Create Universal Router (Solid) Source: https://tanstack.com/router/v1/docs/guide/ssr.md Create a router instance that can be used on both the server and client. This example shows the Solid implementation. ```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 } } ``` -------------------------------- ### Solid Router Instance Setup Source: https://tanstack.com/router/v1/docs/framework/solid/examples/deferred-data Initializes the TanStack Solid Router with the defined route tree, default preload behavior, and scroll restoration. ```typescript const router = createRouter({ routeTree, defaultPreload: 'intent', scrollRestoration: true, }) ``` -------------------------------- ### Without Resolver Example Source: https://tanstack.com/router/v1/docs/api/router/useBlockerHook.md An example of using `useBlocker` without the resolver, directly using browser `confirm` for blocking. ```APIDOC ## Without Resolver ### Description This example shows how to use `useBlocker` without `withResolver: true`, directly prompting the user with `confirm()`. ### Code ```tsx import { useBlocker } from '@tanstack/react-router' import { useState } from 'react' 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 }, }) // ... other component logic return (
{/* Form elements */}
) } ``` ``` -------------------------------- ### React Router Setup with QueryClient Context Source: https://tanstack.com/router/v1/docs/guide/router-context.md Set up a React router with a root route that includes a QueryClient in its context. ```tsx import { createRootRouteWithContext, createRouter, } from '@tanstack/react-router' interface MyRouterContext { queryClient: QueryClient } const rootRoute = createRootRouteWithContext()({ component: App, }) const queryClient = new QueryClient() const router = createRouter({ routeTree: rootRoute, context: { queryClient, }, }) ``` -------------------------------- ### Recommended Legacy Config Setup Source: https://tanstack.com/router/v1/docs/eslint/eslint-plugin-router.md Enable all recommended rules for the TanStack Router ESLint plugin in a legacy `.eslintrc` file. ```json { "extends": ["plugin:@tanstack/eslint-plugin-router/recommended"] } ``` -------------------------------- ### Seed Cache with Route Loader (Naive Example) Source: https://tanstack.com/router/v1/docs/guide/external-data-loading.md Illustrates using a route's `loader` option to seed a cache. This is a naive example and not recommended for production use. ```tsx let postsCache = [] export const Route = createFileRoute('/posts')({ loader: async () => { postsCache = await fetchPosts() }, component: () => { return (
{postsCache.map((post) => ( ))}
) }, }) ``` -------------------------------- ### Example Component Tree Rendering Source: https://tanstack.com/router/v1/docs/routing/route-trees.md Shows the corresponding component tree that would be rendered for the example route hierarchy. ```tsx ``` -------------------------------- ### Solid: Before Virtual Routes Source: https://tanstack.com/router/v1/docs/guide/code-splitting.md Example of Solid route files before utilizing virtual routes, where both the main and lazy files exist. ```tsx import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/posts')({ // Hello? }) ``` ```tsx import { createLazyFileRoute } from '@tanstack/solid-router' export const Route = createLazyFileRoute('/posts')({ component: Posts, }) function Posts() { // ... } ``` -------------------------------- ### fetchOrRedirect Usage Example Source: https://tanstack.com/router/v1/docs/guide/type-utilities.md Example demonstrating how to call `fetchOrRedirect` with a URL and redirect options. The options object is type-checked to ensure it conforms to redirect requirements. ```tsx fetchOrRedirect('http://example.com/', { to: '/login' }) ``` -------------------------------- ### Install TanStack Router for Solid Source: https://tanstack.com/router/v1/docs/quick-start.md Install the TanStack Router package for Solid using your preferred package manager. This command adds the necessary dependency to your project. ```bash @tanstack/solid-router ``` -------------------------------- ### Recommended Flat Config Setup Source: https://tanstack.com/router/v1/docs/eslint/eslint-plugin-router.md Enable all recommended rules for the TanStack Router ESLint plugin in a flat config file. ```javascript import pluginRouter from '@tanstack/eslint-plugin-router' export default [ ...pluginRouter.configs['flat/recommended'], // Any other config... ] ``` -------------------------------- ### SolidJS TanStack Router Main Application Setup Source: https://tanstack.com/router/v1/docs/framework/solid/examples/kitchen-sink This snippet illustrates the core setup for a SolidJS application using TanStack Router, defining the root route, main application component, and global navigation links. ```tsx /* eslint-disable @typescript-eslint/no-unnecessary-condition */ import { render } from 'solid-js/web' import { ErrorComponent, Link, MatchRoute, Outlet, RouterProvider, createRootRouteWithContext, createRoute, createRouter, lazyRouteComponent, redirect, retainSearchParams, useNavigate, useRouter, useRouterState, useSearch, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import { createEffect, createMemo, createRenderEffect, createSignal, on, } from 'solid-js' import { z } from 'zod' import { fetchInvoiceById, fetchInvoices, fetchUserById, fetchUsers, patchInvoice, postInvoice, } from './mockTodos' import { useMutation } from './useMutation' import type { Invoice } from './mockTodos' import './styles.css' // type UsersViewSortBy = 'name' | 'id' | 'email' const rootRoute = createRootRouteWithContext<{ auth: Auth }>()({ component: RootComponent, }) function RouterSpinner() { const isLoading = useRouterState({ select: (s) => s.status === 'pending' }) return } function RootComponent() { return ( <>

Kitchen Sink

{/* Show a global spinner when the router is transitioning */}
{( [ ['/', 'Home'], ['/dashboard', 'Dashboard'], ['/expensive', 'Expensive'], ['/route-a', 'Pathless Layout A'], ['/route-b', 'Pathless Layout B'], ['/profile', 'Profile'], ...(auth.status === 'loggedOut' ? [['/login', 'Login']] : []), ] as const ).map(([to, label]) => { return (
{label}
) })}
{/* Render our first route match */}
) } const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', component: IndexComponent, }) ``` -------------------------------- ### Catch-All Route Params Example Source: https://tanstack.com/router/v1/docs/routing/code-based-routing.md Demonstrates the structure of the params object for a splat/catch-all route. For the URL '/documents/hello-world', '_splat' will contain 'documents/hello-world'. ```js { '_splat': 'documents/hello-world' } ``` -------------------------------- ### URL Matching Example: / Source: https://tanstack.com/router/v1/docs/routing/route-matching.md Illustrates the route matching for the root URL '/'. The root index route is directly matched. ```plaintext Root ✅ / - about/us - about - blog - / - new - $postId - * ``` -------------------------------- ### Create Universal Router (React) Source: https://tanstack.com/router/v1/docs/guide/ssr.md Create a router instance that can be used on both the server and client. This example shows the React implementation. ```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 } } ``` -------------------------------- ### URL Matching Example: /not-a-route Source: https://tanstack.com/router/v1/docs/routing/route-matching.md Demonstrates how a non-existent route like '/not-a-route' is handled. The splat/wildcard route '*' is matched as a fallback. ```plaintext Root ❌ / ❌ about/us ❌ about ❌ blog - / - new - $postId ✅ * ``` -------------------------------- ### React: Before Virtual Routes Source: https://tanstack.com/router/v1/docs/guide/code-splitting.md Example of React route files before utilizing virtual routes, where both the main and lazy files exist. ```tsx import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/posts')({ // Hello? }) ``` ```tsx import { createLazyFileRoute } from '@tanstack/react-router' export const Route = createLazyFileRoute('/posts')({ component: Posts, }) function Posts() { // ... } ``` -------------------------------- ### Create Root Route with Context Source: https://tanstack.com/router/v1/docs/api/router/rootRouteWithContextFunction.md Example of using rootRouteWithContext to define a root route with a specific context type for the router. This setup is now deprecated. ```tsx import { rootRouteWithContext, createRouter } from '@tanstack/react-router' import { QueryClient } from '@tanstack/react-query' interface MyRouterContext { queryClient: QueryClient } const rootRoute = rootRouteWithContext()({ component: () => , // ... root route options }) const routeTree = rootRoute.addChildren([ // ... other routes ]) const queryClient = new QueryClient() const router = createRouter({ routeTree, context: { queryClient, }, }) ``` -------------------------------- ### Solid.js Main Application Setup with TanStack Router Source: https://tanstack.com/router/v1/docs/framework/solid/examples/authenticated-routes Initializes the Solid.js application, sets up the TanStack Router with a context for authentication, and renders the main application wrapped in an AuthProvider. ```typescript import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' import { AuthProvider, useAuth } from './auth' import './styles.css' // Set up a Router instance const router = createRouter({ routeTree, defaultPreload: 'intent', scrollRestoration: true, context: { auth: undefined!, // This will be set after we wrap the app in an AuthProvider }, }) // Register things for typesafety declare module '@tanstack/solid-router' { interface Register { router: typeof router } } function InnerApp() { const auth = useAuth() return } function App() { return ( ) } const rootElement = document.getElementById('app')! render(() => , rootElement) ``` -------------------------------- ### Full Application Setup for Location Masking with Solid Router Source: https://tanstack.com/router/v1/docs/framework/solid/examples/location-masking This comprehensive example illustrates the complete setup for a Solid.js application using TanStack Router to achieve location masking. It includes route definitions, asynchronous data fetching, error handling, and a reusable modal component. ```typescript import type { JSX } from 'solid-js' import { render } from 'solid-js/web' import { ErrorComponent, Link, Outlet, RouterProvider, createRootRoute, createRoute, createRouteMask, createRouter, useNavigate, useRouterState, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import type { ErrorComponentProps } from '@tanstack/solid-router' import './styles.css' type PhotoType = { id: string title: string url: string thumbnailUrl: string albumId: string } class NotFoundError extends Error {} const fetchPhotos = async () => { console.info('Fetching photos...') await new Promise((r) => setTimeout(r, 500)) // Generate mock photos using picsum.photos since via.placeholder.com is down return Array.from({ length: 10 }, (_, i) => ({ id: String(i + 1), title: `Photo ${i + 1}`, url: `https://picsum.photos/600/400?random=${i + 1}`, thumbnailUrl: `https://picsum.photos/200/200?random=${i + 1}`, albumId: '1', })) } const fetchPhoto = async (photoId: string) => { console.info(`Fetching photo with id ${photoId}...`) await new Promise((r) => setTimeout(r, 500)) // Simulate photo not found for invalid IDs const photoIdNum = parseInt(photoId, 10) if (isNaN(photoIdNum) || photoIdNum < 1 || photoIdNum > 10) { throw new NotFoundError(`Photo with id "${photoId}" not found!`) } // Generate mock photo using picsum.photos return { id: photoId, title: `Photo ${photoId}`, url: `https://picsum.photos/600/400?random=${photoId}`, thumbnailUrl: `https://picsum.photos/200/200?random=${photoId}`, albumId: '1', } } type PhotoModal = { id: 'photo' photoId: string } type ModalObject = PhotoModal export function Spinner() { return (
) } const rootRoute = createRootRoute({ validateSearch: (search) => search as { modal?: ModalObject }, component: RootComponent, }) function RootComponent() { const status = useRouterState({ select: (s) => s.status }) return ( <>
Home {' '} Photos {' '} {status() === 'pending' ? : null}

{/* Start rendering router matches */} ) } function Modal(props: { children: JSX.Element onOpenChange?: (open: boolean) => void }) { const handleOverlayClick = () => { props.onOpenChange?.(false) } const handleContentClick = (e: MouseEvent) => { e.stopPropagation() } return (
{props.children}
) } ``` -------------------------------- ### SolidJS Application Setup with TanStack Router and Solid Query Source: https://tanstack.com/router/v1/docs/framework/solid/examples/kitchen-sink-solid-query-file-based This snippet demonstrates the main application entry point, configuring TanStack Router with Solid Query, setting up default pending and error components, and integrating session storage for dynamic loader and pending delays. ```typescript import { render } from 'solid-js/web' import { ErrorComponent, RouterProvider, createRouter, } from '@tanstack/solid-router' import { QueryClient, QueryClientProvider } from '@tanstack/solid-query' import { auth } from './utils/auth' import { Spinner } from './components/Spinner' import { routeTree } from './routeTree.gen' import { useSessionStorage } from './hooks/useSessionStorage' import './styles.css' // export const queryClient = new QueryClient() const router = createRouter({ routeTree, defaultPendingComponent: () => (
true} />
), defaultErrorComponent: ({ error }) => , context: { auth: undefined!, // We'll inject this when we render queryClient: queryClient, // Type assertion to fix the type mismatch }, defaultPreload: 'intent', // Since we're using Solid Query, we don't want loader calls to ever be stale // This will ensure that the loader is always called when the route is preloaded or visited defaultPreloadStaleTime: 0, scrollRestoration: true, }) declare module '@tanstack/solid-router' { interface Register { router: typeof router } } function App() { // This stuff is just to tweak our sandbox setup in real-time const [loaderDelay, setLoaderDelay] = useSessionStorage('loaderDelay', 500) const [pendingMs, setPendingMs] = useSessionStorage('pendingMs', 1000) const [pendingMinMs, setPendingMinMs] = useSessionStorage('pendingMinMs', 500) return ( <>
Loader Delay: {loaderDelay()}ms
setLoaderDelay(e.target.valueAsNumber)} class="w-full" />
defaultPendingMs: {pendingMs()}ms
setPendingMs(e.target.valueAsNumber)} class="w-full" />
defaultPendingMinMs: {pendingMinMs()}ms
setPendingMinMs(e.target.valueAsNumber)} class="w-full" />
) } const rootElement = document.getElementById('app')! if (!rootElement.innerHTML) { render( () => ( ), rootElement, ) } ``` -------------------------------- ### Scaffold New TanStack Router Project (React) Source: https://tanstack.com/router/v1/docs/quick-start.md Use the TanStack CLI to create a new project with router-only setup for React. The CLI will guide you through customization options. ```bash @tanstack/cli create --router-only ``` -------------------------------- ### Route File Naming Examples Source: https://tanstack.com/router/v1/docs/api/file-based-routing.md Demonstrates how different file naming conventions map to runtime URLs. Files like `posts.tsx`, `posts.route.tsx`, and `posts/route.tsx` all resolve to the `/posts` URL. ```txt src/routes/posts.tsx -> /posts src/routes/posts.route.tsx -> /posts src/routes/posts/route.tsx -> /posts ``` -------------------------------- ### Initialize Query Client and Router in Solid Source: https://tanstack.com/router/v1/docs/framework/solid/examples/kitchen-sink-solid-query Initializes a `QueryClient` and configures the main router with the route tree, default components, context, and preloading behavior. ```typescript const queryClient = new QueryClient() const router = createRouter({ routeTree, defaultPendingComponent: () => (
), defaultErrorComponent: ({ error }) => , context: { auth: undefined!, // We'll inject this when we render queryClient, }, defaultPreload: 'intent', // Since we're using React Query, we don't want loader calls to ever be stale // This will ensure that the loader is always called when the route is preloaded or visited defaultPreloadStaleTime: 0, scrollRestoration: true, }) ``` -------------------------------- ### Advanced Programmatic Code Splitting with Vite Source: https://tanstack.com/router/v1/docs/guide/automatic-code-splitting.md Use the `splitBehavior` function in `vite.config.ts` for complex code splitting rules based on `routeId`. This example bundles `loader` and `component` for routes starting with `/posts`. ```ts import { defineConfig } from 'vite' import { tanstackRouter } from '@tanstack/router-plugin/vite' export default defineConfig({ plugins: [ tanstackRouter({ autoCodeSplitting: true, codeSplittingOptions: { splitBehavior: ({ routeId }) => { // For all routes under /posts, bundle the loader and component together if (routeId.startsWith('/posts')) { return [['loader', 'component']] } // All other routes will use the `defaultBehavior` }, }, }), ], }) ``` -------------------------------- ### URL Matching Example: /blog Source: https://tanstack.com/router/v1/docs/routing/route-matching.md Demonstrates how the route tree is matched for the URL '/blog'. The 'blog' route is matched, and its index route '/' is selected. ```plaintext Root ❌ / ❌ about/us ❌ about ⏩ blog ✅ / - new - $postId - * ``` -------------------------------- ### Install ESLint Plugin Router Source: https://tanstack.com/router/v1/docs/eslint/eslint-plugin-router.md Install the ESLint plugin for TanStack Router as a development dependency. ```bash npm install -D @tanstack/eslint-plugin-router ``` ```bash yarn add -D @tanstack/eslint-plugin-router ``` ```bash pnpm add -D @tanstack/eslint-plugin-router ``` -------------------------------- ### Conditional Blocking Example Source: https://tanstack.com/router/v1/docs/api/router/useBlockerHook.md An example showing how to conditionally block navigation based on the properties of the next route. ```APIDOC ## Conditional Blocking ### Description This example demonstrates blocking navigation unless the target route's pathname includes '/step/'. ### Code ```tsx import { useBlocker } from '@tanstack/react-router' function MyComponent() { const { proceed, reset, status } = useBlocker({ shouldBlockFn: ({ next }) => { return !next.pathname.includes('step/') }, withResolver: true, }) // ... other component logic return (
{/* Content */} {status === 'blocked' && (

Are you sure you want to leave?

)}
) } ``` ``` -------------------------------- ### Solid.js Application Setup with Data Fetching and Motion Transitions Source: https://tanstack.com/router/v1/docs/framework/solid/examples/with-framer-motion This snippet defines the core application structure, including imports for Solid.js, `solid-motionone`, and `@tanstack/solid-router`. It also sets up data fetching functions for posts and defines transition properties for Framer Motion. ```typescript import { render } from 'solid-js/web' import { Motion, Presence } from 'solid-motionone' import { ErrorComponent, Link, Outlet, RouterProvider, createRootRoute, createRoute, createRouter, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import axios from 'redaxios' import './styles.css' type PostType = { id: string title: string body: string } const fetchPosts = async () => { console.info('Fetching posts...') await new Promise((r) => setTimeout(r, 500)) return axios .get>('https://jsonplaceholder.typicode.com/posts') .then((r) => r.data.slice(0, 10)) } const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) await new Promise((r) => setTimeout(r, 500)) const post = await axios .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) .then((r) => r.data) // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!post) { throw new NotFoundError(`Post with id "${postId}" not found!`) } return post } export const mainTransitionProps = { initial: { y: -20, opacity: 0 }, animate: { y: 0, opacity: 1 }, exit: { y: 60, opacity: 0 }, transition: { duration: 0.3, easing: 'ease-out', }, } as const export const postTransitionProps = { initial: { y: -20, opacity: 0 }, animate: { y: 0, opacity: 1 }, exit: { y: 60, opacity: 0 }, transition: { duration: 0.3, easing: 'ease-out', }, } as const ``` -------------------------------- ### Initialize TanStack Router with Solid Query and Render Application Source: https://tanstack.com/router/v1/docs/framework/solid/examples/basic-solid-query This snippet sets up a TanStack Router instance, configures it with a QueryClient for data fetching, registers the router for type safety, and renders the Solid application using QueryClientProvider and RouterProvider. ```typescript const router = createRouter({ routeTree, defaultPreload: 'intent', // Since we're using React Query, we don't want loader calls to ever be stale // This will ensure that the loader is always called when the route is preloaded or visited defaultPreloadStaleTime: 0, scrollRestoration: true, context: { queryClient, }, }) // Register things for typesafety declare module '@tanstack/solid-router' { interface Register { router: typeof router } } const rootElement = document.getElementById('app')! if (!rootElement.innerHTML) { render( () => ( ), rootElement, ) } ``` -------------------------------- ### Project Dependencies for SolidJS Router Quickstart Source: https://tanstack.com/router/v1/docs/framework/solid/examples/quickstart This `package.json` outlines the necessary dependencies for a SolidJS project using TanStack Router, including SolidJS, router libraries, and build tools. ```json { "name": "tanstack-router-solid-example-quickstart", "private": true, "type": "module", "scripts": { "dev": "vite --port 3000", "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-router": "^1.170.16", "@tanstack/solid-router-devtools": "^1.167.0", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, "devDependencies": { "vite-plugin-solid": "^2.11.11", "typescript": "^6.0.2", "vite": "^8.0.14" } } ``` -------------------------------- ### Install TanStack Router for React Source: https://tanstack.com/router/v1/docs/quick-start.md Install the TanStack Router package for React using your preferred package manager. This command adds the necessary dependency to your project. ```bash @tanstack/react-router ``` -------------------------------- ### Create Router with Context (Solid) Source: https://tanstack.com/router/v1/docs/guide/router-context.md Create the router instance and provide the initial context values for your Solid application. ```tsx import { createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' const router = createRouter({ routeTree, context: { foo: true, }, }) ``` -------------------------------- ### Menu Component Usage Example Source: https://tanstack.com/router/v1/docs/guide/type-utilities.md Example of using the Menu component with relative navigation paths. The `from` prop sets the base path, and `items` define the links relative to it. ```tsx ``` -------------------------------- ### Create TanStack Router Instance in Solid Source: https://tanstack.com/router/v1/docs/framework/solid/examples/kitchen-sink Initializes the router with the defined route tree, custom pending and error components, context, and default preload behavior. ```tsx const router = createRouter({ routeTree, defaultPendingComponent: () => (
), defaultErrorComponent: ({ error }) => , context: { auth: undefined!, // We'll inject this when we render }, defaultPreload: 'intent', scrollRestoration: true, }) ``` -------------------------------- ### Solid Layout Route Example Source: https://tanstack.com/router/v1/docs/routing/routing-concepts.md Define a layout route in Solid using `createFileRoute` and `Outlet` to render child routes within a layout component. This example shows a basic app layout. ```tsx import { Outlet, createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/app')({ component: AppLayoutComponent, }) function AppLayoutComponent() { return (

App Layout

) } ``` -------------------------------- ### React Layout Route Example Source: https://tanstack.com/router/v1/docs/routing/routing-concepts.md Define a layout route in React using `createFileRoute` and `Outlet` to render child routes within a layout component. This example shows a basic app layout. ```tsx import { Outlet, createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/app')({ component: AppLayoutComponent, }) function AppLayoutComponent() { return (

App Layout

) } ```