Rule
0 installs · 0 said it worked
Cursor rules for building type-safe TanStack Router apps in React
Cursor rules that guide the AI to write TanStack Router v1 code in React and TypeScript, covering file-based routing, typed params, Zod search validation, loaders, auth guards, and preloading.
People use this for
- tanstack router react rules
- typed routes react typescript
- react router search params zod
- cursor rules react routing
- how to write type-safe react routes
- Name
cursor-rules-for-building-type-safe-tanstack-router-apps-in-reac- Works with
- Cursor
- License
- CC0(as observed at the source)
- Version
- v1 · updated Nov 29, 2026
Imported on Nov 29, 2026 from github.com . License observed at the source on Nov 29, 2026: CC0.
Are you the author?Claim this profileRequest removal
Use this rule
$ curl -fsSL "https://promptcommunity.dev/api/v1/posts/cursor-rules-for-building-type-safe-tanstack-router-apps-in-react-mw54/export/mdc" -o .cursor/rules/cursor-rules-for-building-type-safe-tanstack-router-apps-in-reac.mdcThen open a new session; Cursor picks it up from .cursor/rules/.
Manual install
Save cursor-rules-for-building-type-safe-tanstack-router-apps-in-reac.mdc as .cursor/rules/cursor-rules-for-building-type-safe-tanstack-router-apps-in-reac.mdc for this project or ~/.cursor/rules/cursor-rules-for-building-type-safe-tanstack-router-apps-in-reac.mdc for every project, then start a new session.
Rule
description: "Cursor rules for TanStack Router v1 with file-based routing, typed params, search validation, loaders, auth guards, and route preloading." globs: */ alwaysApply: false
You are an expert in TanStack Router, React, TypeScript, and modern type-safe client-side routing.
TanStack Router + React Guidelines
Core Philosophy
- TanStack Router is 100% type-safe — leverage TypeScript generics for route params, search params, and loader data
- Prefer file-based routing for scalability; use code-based routing only for highly dynamic use cases
- Always define routes with
createFileRouteorcreateRootRoute— never use plain objects - Route data loading belongs in
loaderfunctions, not in componentuseEffect - Search params are first-class citizens — define their schema with Zod or Valibot for validation and type inference
Project Setup
- Use
@tanstack/react-routerwith Vite and the@tanstack/router-vite-pluginfor file-based routing - Enable
routeTree.gen.tsauto-generation — never manually edit this file - Structure routes under
src/routes/directory - Root layout goes in
src/routes/__root.tsx - Use
src/routes/index.tsxfor the home/index route
File-Based Route Conventions
src/routes/
__root.tsx ← Root layout (wraps all routes)
index.tsx ← / route
about.tsx ← /about route
posts/
index.tsx ← /posts route
$postId.tsx ← /posts/:postId (dynamic segment)
_layout.tsx ← Layout route (no path segment)
_auth/
login.tsx ← /login (grouped under auth layout)
(admin)/
dashboard.tsx ← /dashboard (pathless group)
Route Definition Patterns
// src/routes/posts/$postId.tsx
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/posts/$postId')({
loader: async ({ params }) => {
return fetchPost(params.postId) // fully typed params
},
component: PostComponent,
})
function PostComponent() {
const post = Route.useLoaderData() // type-safe loader data
const { postId } = Route.useParams() // type-safe params
return <div>{post.title}</div>
}
Type-Safe Search Params
- Always define search param schemas using
z.object()from Zod - Use
validateSearchoption on route definition - Access with
Route.useSearch()— never read rawwindow.location.search
import { z } from 'zod'
import { createFileRoute } from '@tanstack/react-router'
const searchSchema = z.object({
page: z.number().int().min(1).default(1),
q: z.string().optional(),
})
export const Route = createFileRoute('/search')({
validateSearch: searchSchema,
component: SearchPage,
})
function SearchPage() {
const { page, q } = Route.useSearch()
// ...
}
Navigation
- Use
<Link>from@tanstack/react-router— never<a href>for internal navigation - Use
useNavigate()for programmatic navigation - Always pass typed
paramsandsearchto Link — the compiler will catch mistakes
import { Link, useNavigate } from '@tanstack/react-router'
// Declarative
<Link to="/posts/$postId" params={{ postId: '123' }}>View Post</Link>
// Programmatic
const navigate = useNavigate()
navigate({ to: '/posts/$postId', params: { postId: post.id } })
Loaders & Data Fetching
- Use
loaderfor data that must be available before render (no loading spinners for critical data) - Integrate with TanStack Query by using
ensureQueryDatainside loaders for caching - Use
staleTimeon loaders to avoid redundant fetches during navigation - Return plain serializable data from loaders — no class instances
export const Route = createFileRoute('/posts')({
loader: ({ context: { queryClient } }) =>
queryClient.ensureQueryData(postsQueryOptions()),
component: PostsPage,
})
Error Handling
- Define
errorComponenton routes to handle loader or render errors - Use
notFoundComponentfor 404 states within a route subtree - Use
pendingComponentfor showing skeletons/spinners during data loading
export const Route = createFileRoute('/posts/$postId')({
loader: fetchPost,
errorComponent: ({ error }) => <ErrorBanner message={error.message} />,
pendingComponent: () => <PostSkeleton />,
notFoundComponent: () => <NotFound />,
component: PostDetail,
})
Router Context
- Use router context to inject global dependencies (queryClient, auth, theme) into loaders
- Define context type in
__root.tsxand pass it when creating the router
// __root.tsx
import { createRootRouteWithContext } from '@tanstack/react-router'
interface RouterContext {
queryClient: QueryClient
auth: AuthState
}
export const Route = createRootRouteWithContext<RouterContext>()({
component: RootLayout,
})
// main.tsx
const router = createRouter({
routeTree,
context: { queryClient, auth },
})
Route Guards / Auth
- Use
beforeLoadfor authentication checks — redirect to login if unauthenticated - Never put auth logic inside components — handle it at the routing layer
export const Route = createFileRoute('/_auth/dashboard')({
beforeLoad: ({ context }) => {
if (!context.auth.isAuthenticated) {
throw redirect({ to: '/login' })
}
},
component: Dashboard,
})
Performance
- Use
preloadon<Link>to trigger loader prefetching on hover/focus - Set
defaultPreload: 'intent'on the router for automatic preloading - Use
gcTimeandstaleTimeon loaders to tune cache behavior - Lazy-load route components with
React.lazyfor code splitting
DevTools
- Install
@tanstack/router-devtoolsand render<TanStackRouterDevtools />in development - Use devtools to inspect route tree, active matches, loader data, and search params
Testing
- Use
createMemoryHistoryandcreateRouterto create isolated router instances in tests - Wrap components under test with
<RouterProvider router={testRouter} /> - Mock loaders by providing fake context values
No result recorded yet. Added it? File a Tried-it report so the next person knows how it went in your editor.
Tried it
Reports from people who added this rule to their editor. They roll up into the badges above.
No one has filed a report yet. Try the prompt and be the first.
Related rules
- Autonomous coding agent that builds a verified app-builder harness
Master system prompt that directs an autonomous senior Python engineer to build a spec-driven, evidence-traced app-builder harness milestone by milestone without asking questions.
Coding · @mahfuzahmedog
- Data validation architect role for multi-layer input validation and sanitization
A role prompt that turns the model into a senior data integrity expert who designs multi-layer input validation, sanitization, injection prevention, and error handling, and writes the plan to a TODO_data-validator.md checklist file.
Coding · @wkaandemir
- Cursor rules for type-safe TanStack Router v1 React routing
Cursor rule set guiding an assistant to build type-safe React routing with TanStack Router v1, covering file-based routes, loaders, Zod-validated search params, auth guards, and TanStack Query integration.
Coding · @patrickjs
- Claude api: reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming,…
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any fo
Coding · @anthropic
- Agent role that turns TypeScript typing work into a tracked TODO plan
A senior TypeScript type-expert role prompt covering type design, generics, narrowing, and migration, with a required output of TODO_ts-type-expert.md containing checkable task items.
Coding · @wkaandemir
License: CC0v1 · published Nov 29, 2026
Comments
No comments yet. If you tried this prompt, say how it went.