Skip to content

Volume ITechnology

6.4.12 — TanStack Router: Routing That the Compiler Checks ​

A shop has a link to a product: <Link to={/products/${id}}>. Six months later someone renames the route to /items/:id. Nothing warns anyone. The old links all lead to a "not found" page, and the first person to notice is a customer.

Page 6.4.9 taught React Router. Its paths are plain text, so a typo is just a string that happens to be wrong. TanStack Router is built around a different idea: the router knows every route, every URL parameter and every search value as a TypeScript type. A wrong link does not compile. This page teaches it with the same shop, so you can compare the two directly.

1. What "typed routes" means, in three examples ​

Here are three mistakes in a link. With TanStack Router, the editor underlines each one, and the build fails:

tsx
<Link to="/prodcts">Products</Link>
// error: Type '"/prodcts"' is not assignable to type '"." | ".." | "/" | "/products" | "/products/$productId"'.
//        Did you mean '"/products"'?

<Link to="/products/$productId">Lamp</Link>
// error: Property 'params' is missing ...      (the route needs a productId)

<Link to="/products" search={{ sort: 'colour' }}>Sorted</Link>
// error: Type '"colour"' is not assignable to type '"name" | "price" | undefined'.

We ran exactly these through the TypeScript compiler, and those are its messages (shortened). The first is a typo in the path. The second forgot the parameter. The third used a sort value that the route does not allow. In every case you find out while typing, not in production.

Autocomplete works too: when you type to=", the editor lists the real routes.

How it can know ​

React Router reads its route list at runtime, so TypeScript cannot see it. TanStack Router uses a file per route. A small tool reads the folder and writes a file, routeTree.gen.ts, that describes every route as types. TypeScript reads that file, and from then on it knows the whole URL map.

① Route filesroutes/__root.tsxroutes/index.tsxroutes/products/index.tsxroutes/products/$productId.tsx② Generatorplugin on every save,or npx tsr generatewrites routeTree.gen.ts③ Types registered'/' '/products''/products/$productId'params and search shapes④ Your code is checkedLink to "/products/$productId" + its paramsnavigate to "/products" + search sortWrong link?red underline in the editor,and the build fails
Why TanStack Router can check your links. One file per route goes in; a small tool writes one generated file that describes every route as types; TypeScript then checks every link, parameter and search value against it.

The figure shows the loop. You write route files (①). The tool writes the generated file (②). That file registers the types (③). Now every Link, navigate and useParams in your app is checked against them (④).

2. Set it up ​

bash
npm install @tanstack/react-router
npm install -D @tanstack/router-plugin

The plugin runs the generator for you whenever you save a route file. With Vite, add it before the React plugin:

ts
// 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', autoCodeSplitting: true }),                  // (1)
    react(),
  ],
})
  1. target: 'react' picks the React flavor. autoCodeSplitting: true makes each route's code load only when that route is visited, which is the lazy idea from page 6.4.9, done for you.

(Without a bundler plugin, you can run npx tsr generate once by hand. It does the same job.)

3. Routes are files ​

The path of the file is the URL. We build the same shop as on page 6.4.9:

FileURLWhat it is
src/routes/__root.tsxevery URLThe outer layout. It holds the header and <Outlet />
src/routes/index.tsx/Home
src/routes/products/index.tsx/productsThe product list
src/routes/products/$productId.tsx/products/p2One product. $ marks a parameter
src/routes/login.tsx/loginThe login page
src/routes/_auth.tsxnoneA layout without a URL that guards its children. _ means "no path segment"
src/routes/_auth/account.tsx/accountA page that needs a login

We generated the route tree for exactly this layout and the tool produced the URLs in the right-hand column. Note two things. $productId in a file name becomes :productId in React Router terms. And _auth is a trick for sharing something (here, a login check) between several routes without adding anything to their URLs.

The root route ​

tsx
// src/routes/__root.tsx
import { createRootRouteWithContext, Link, Outlet } from '@tanstack/react-router'
import type { QueryClient } from '@tanstack/react-query'

export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()({   // (1)
  component: RootLayout,
  notFoundComponent: () => (                                                         // (2)
    <section>
      <h1>Page not found</h1>
      <Link to="/products">See all products</Link>
    </section>
  ),
})

function RootLayout() {
  return (
    <>
      <header>
        <nav>
          <Link to="/" activeOptions={{ exact: true }} activeProps={{ className: 'active' }}>   {/* (3) */}
            Home
          </Link>
          <Link to="/products" activeProps={{ className: 'active' }}>
            Products
          </Link>
        </nav>
      </header>
      <main>
        <Outlet />
      </main>
    </>
  )
}
  1. createRootRouteWithContext lets you hand shared things to every route: here the QueryClient from page 6.4.10. The extra () is a TypeScript detail: you write it exactly like that. Every loader and guard can now reach context.queryClient.
  2. What to show when no route matches. We tested /nothing and without this it shows a bare "Not Found" line, and the console warns you to set one.
  3. activeProps are props applied only while the link is the current page. activeOptions={{ exact: true }} keeps the Home link from being active everywhere, like end in React Router.

Pages ​

tsx
// src/routes/index.tsx
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/')({                                          // (1)
  component: () => <h1>Welcome to the shop</h1>,
})
  1. Every route file exports a Route. createFileRoute('/') takes the route's own path. The tool fills this string in for you when you create a new file, and it checks that it matches the file name. That is how the types stay joined to the files.

The product list uses search params, so we look at those next.

4. Search params with a check on them ​

Remember from page 6.4.9: filters belong in the URL (/products?q=lamp&sort=price). In React Router, searchParams.get('sort') gives you a plain string or null, and you must check it. In TanStack Router, a route declares what its search params may look like, and everything after that is typed.

The declaration is a function called validateSearch. It receives whatever is in the URL (which a user can type by hand, so it can be anything) and returns a clean object.

tsx
// src/routes/products/index.tsx
import { createFileRoute, Link } from '@tanstack/react-router'
import { fetchProducts } from '../../api/products'

type Sort = 'name' | 'price'

function toSort(value: unknown): Sort | undefined {                                  // (1)
  return value === 'name' || value === 'price' ? value : undefined
}

export const Route = createFileRoute('/products/')({
  validateSearch: (search: Record<string, unknown>): { q?: string; sort?: Sort } => ({   // (2)
    q: typeof search.q === 'string' ? search.q : undefined,
    sort: toSort(search.sort),
  }),
  loaderDeps: ({ search }) => ({ q: search.q ?? '' }),                               // (3)
  loader: ({ deps }) => fetchProducts(deps.q),                                       // (4)
  component: ProductsPage,
})

function ProductsPage() {
  const products = Route.useLoaderData()                                             // (5)
  const { q = '', sort = 'name' } = Route.useSearch()                                // (6)

  const sorted = [...products].sort((a, b) =>
    sort === 'price' ? a.priceCents - b.priceCents : a.name.localeCompare(b.name),
  )

  return (
    <>
      <p>
        Search: {q === '' ? 'everything' : q} · sorted by {sort}
      </p>
      <Link to="/products" search={(prev) => ({ ...prev, sort: sort === 'price' ? 'name' : 'price' })}>   {/* (7) */}
        Sort by {sort === 'price' ? 'name' : 'price'}
      </Link>
      <ul>
        {sorted.map((p) => (
          <li key={p.id}>
            <Link to="/products/$productId" params={{ productId: p.id }}>{p.name}</Link>    {/* (8) */}
          </li>
        ))}
      </ul>
    </>
  )
}
  1. A small function that accepts only the two sort words we support. For anything else, including a missing value, it returns undefined.
  2. validateSearch gets the raw search object. Its type is Record<string, unknown>: "some keys, values of any kind". We cannot trust it, because a user can type anything after the ?. We return an object with the declared type { q?: string; sort?: Sort }, where the question marks mean "may be missing". That declared type is what the rest of the route sees, and what Link checks. Because both fields are optional, a link to /products needs no search at all. We checked a URL of /products?sort=junk&q=lamp: the page drew with q=lamp, sort fell back to name, and the cleaned search object in the router was { q: 'lamp' }. A bad value does not crash anything.
  3. A loader cannot read the search params directly. You must list the ones it depends on in loaderDeps. This is how the router knows to run the loader again when q changes, but not when only sort changes (which we sort in the browser anyway).
  4. The loader receives deps. It returns the data.
  5. Route.useLoaderData() reads the loader's result, fully typed.
  6. Route.useSearch() reads the validated search. We give defaults here, in the component, so the URL stays clean when the value is the default.
  7. search can be a function that receives the current search and returns the new one. We copy it with ...prev so q is kept when only sort changes. The types check that 'price' and 'name' are the only values.
  8. params={{ productId: p.id }} is required, because the target route has $productId. Leave it out and it will not compile.

The fake API used above, in a small file:

ts
// src/api/products.ts
export type Product = { id: string; name: string; priceCents: number }

const products: Product[] = [
  { id: 'p1', name: 'Red mug', priceCents: 1999 },
  { id: 'p2', name: 'Desk lamp', priceCents: 4500 },
  { id: 'p3', name: 'Notebook', priceCents: 650 },
]

const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

export async function fetchProducts(query: string): Promise<Product[]> {
  await pause(50)
  return products.filter((p) => p.name.toLowerCase().includes(query.toLowerCase()))
}

export async function fetchProduct(id: string): Promise<Product | undefined> {
  await pause(50)
  return products.find((p) => p.id === id)
}

Doing the same with a library ​

Writing validateSearch by hand is clear but gets long for many fields. A validation library such as Zod describes the allowed shape in fewer lines and also gives you the type. Page 6.4.13 teaches it fully. As a preview, this is the same check, and it works because the router accepts any validator that follows a shared standard:

ts
import { z } from 'zod'

const searchSchema = z.object({
  q: z.string().optional().catch(undefined),                       // text, or nothing; bad input becomes nothing
  sort: z.enum(['name', 'price']).optional().catch(undefined),     // one of two words, or nothing
})

// validateSearch: searchSchema

.catch(undefined) means "if the value is wrong, use undefined instead of failing". We compiled and ran it. The result was the same as the hand-written version.

5. A page that needs a parameter ​

tsx
// src/routes/products/$productId.tsx
import { createFileRoute, notFound } from '@tanstack/react-router'
import { fetchProduct } from '../../api/products'

export const Route = createFileRoute('/products/$productId')({
  loader: async ({ params }) => {                                                    // (1)
    const product = await fetchProduct(params.productId)                             // (2)
    if (!product) throw notFound()                                                   // (3)
    return product
  },
  pendingComponent: () => <p>Loading product…</p>,                                   // (4)
  errorComponent: ({ error }) => <p role="alert">Something went wrong: {error.message}</p>,   // (5)
  notFoundComponent: () => <p>We could not find that product.</p>,                   // (6)
  component: ProductPage,
})

function ProductPage() {
  const product = Route.useLoaderData()
  const { productId } = Route.useParams()                                            // (7)

  return (
    <article>
      <h1>{product.name}</h1>
      <p>${(product.priceCents / 100).toFixed(2)}</p>
      <small>Product id: {productId}</small>
    </article>
  )
}
  1. The loader runs before the page draws, like in React Router.
  2. params.productId is a string. It is not string | undefined, because the router knows this route has that parameter.
  3. A missing product: notFound() makes the router show this route's notFoundComponent.
  4. Drawn while the loader is waiting (after a short delay, so quick loads do not flash it).
  5. Drawn if the loader or the page throws. It receives the error.
  6. Drawn by notFound(). We tested /products/zzz and it showed this text inside the layout, with the header still there.
  7. Route.useParams() gives typed params. Notice you call the hook on the route object, not on a global useParams. That is how it knows which route's params to give you.

6. A page that needs a login: beforeLoad ​

beforeLoad runs before the loader, and before any child route. It is the place for checks, and for redirects.

tsx
// src/routes/_auth.tsx
import { createFileRoute, Outlet, redirect } from '@tanstack/react-router'

function isLoggedIn(): boolean {
  return localStorage.getItem('token') !== null
}

export const Route = createFileRoute('/_auth')({
  beforeLoad: ({ location }) => {
    if (!isLoggedIn()) {
      throw redirect({ to: '/login', search: { from: location.href } })              // (1)
    }
  },
  component: () => <Outlet />,                                                       // (2)
})
tsx
// src/routes/_auth/account.tsx
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/_auth/account')({
  component: () => <h1>My account</h1>,
})
tsx
// src/routes/login.tsx
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/login')({
  component: () => <h1>Please log in</h1>,
})
  1. If the user is not logged in, send them to /login, and remember where they came from in the search params (?from=%2Faccount), so after login you can send them back. We ran it: opening /account while logged out ended on /login?from=%2Faccount. After setting the flag to logged in, /account showed the account page.
  2. The guard route draws nothing itself. It only passes the child through with <Outlet />.

Because account.tsx lives inside the _auth folder, it is protected, and its URL is still just /account. Put any number of pages in that folder and they are all protected by this one check. As on page 6.4.9, remember that this protects the screen. The real protection of private data is on the server, which must check the token on every request.

7. Create the router and start the app ​

tsx
// src/router.tsx
import { createRouter } from '@tanstack/react-router'
import { QueryClient } from '@tanstack/react-query'
import { routeTree } from './routeTree.gen'

export const queryClient = new QueryClient()

export const router = createRouter({
  routeTree,                                                                         // (1)
  context: { queryClient },                                                          // (2)
  defaultPreload: 'intent',                                                          // (3)
})

declare module '@tanstack/react-router' {
  interface Register {
    router: typeof router                                                            // (4)
  }
}
tsx
// src/main.tsx
import { createRoot } from 'react-dom/client'
import { RouterProvider } from '@tanstack/react-router'
import { QueryClientProvider } from '@tanstack/react-query'
import { queryClient, router } from './router'

createRoot(document.getElementById('root')!).render(
  <QueryClientProvider client={queryClient}>
    <RouterProvider router={router} />
  </QueryClientProvider>,
)
  1. routeTree comes from the generated file. You never edit it.
  2. The value for the context we declared on the root route. It is checked: if you forget it, TypeScript complains.
  3. 'intent' means: when the user hovers over a link or touches it, start loading that route's code and data. By the time they click, much of the work is done. This is the same idea as the prefetch-on-hover you wrote by hand on page 6.4.11, as one setting.
  4. This is the step that makes everything typed. This block of TypeScript, called a declaration merge, tells the library "the router of this app is this one". After that, Link, useNavigate and every hook know your routes.

8. With TanStack Query ​

Page 6.4.11 showed how a router loader and the Query cache work together. TanStack Router is built for it, because the context we put on the root gives every loader the queryClient. Here is an orders page.

ts
// src/api/orders.ts
import { queryOptions } from '@tanstack/react-query'

export type Order = { id: string; total: number }

export const ordersOptions = () =>
  queryOptions({
    queryKey: ['orders'],
    queryFn: async (): Promise<Order[]> => [{ id: 'o1', total: 6499 }],                // stand-in for a fetch
    staleTime: 30_000,
  })
tsx
// src/routes/_auth/orders.tsx
import { createFileRoute } from '@tanstack/react-router'
import { useSuspenseQuery } from '@tanstack/react-query'
import { ordersOptions } from '../../api/orders'

export const Route = createFileRoute('/_auth/orders')({
  loader: ({ context }) => context.queryClient.ensureQueryData(ordersOptions()),    // (1)
  component: OrdersPage,
})

function OrdersPage() {
  const { data: orders } = useSuspenseQuery(ordersOptions())                         // (2)

  return (
    <ul>
      {orders.map((o) => (
        <li key={o.id}>
          {o.id}: ${(o.total / 100).toFixed(2)}
        </li>
      ))}
    </ul>
  )
}
  1. The loader puts the data into the Query cache, or finds it there already. Because it returns the promise, the router waits for it before drawing.
  2. useSuspenseQuery is a version of useQuery for when the data is guaranteed to be ready. It never returns undefined, so there is no if (isPending) check. The loader has already made sure the data is in the cache. Later changes, like a mutation's invalidateQueries, update the page, because the component still watches the cache.

You get both: no loading flash on arrival from the loader, and caching and refreshing from Query.

9. Moving around in code ​

tsx
import { useNavigate } from '@tanstack/react-router'

function CheckoutDone() {
  const navigate = useNavigate()
  return (
    <button onClick={() => navigate({ to: '/products', search: { sort: 'price' } })}>
      Back to the shop
    </button>
  )
}

navigate takes the same typed options as Link: to, params, search. A typo is a compile error here too. We used router.navigate the same way in our tests and the URL became /products?sort=price.

10. React Router or TanStack Router? ​

React Router (data mode)TanStack Router
Route listone array in codeone file per route (or code)
Type checking of links and paramsnoyes, from the generated file
Search paramsstrings you parse yourselfvalidated and typed
Loader reruns when search changesautomaticyou list loaderDeps
Preloading on hoveryou write itone setting (defaultPreload)
How common in existing codevery commongrowing fast
Extra setuplittleplugin and generated file

Pick TanStack Router for a new TypeScript app where wrong links should be caught early, and where filters in the URL matter. Pick React Router when you join a codebase that already uses it, which is very common, or when you use a framework built on it (Chapter 6.5). The ideas you learned on page 6.4.9 (nested layouts, Outlet, loaders, redirects, params, errors) are the same here with different names. Knowing one means you can read the other in an afternoon.

What the interviewer will push on ​

"What is the main difference between TanStack Router and React Router?" Type safety. TanStack Router generates types from the route files, so Link, navigate, params and search params are checked at compile time. A broken link fails the build. Then mention file-based routes and built-in search param validation.

"How do search params work in TanStack Router?" The route declares validateSearch, which turns untrusted URL text into a typed object (by hand or with a library like Zod). Components read it with Route.useSearch(). A loader declares loaderDeps for the search values it needs, so it reruns when they change.

"How would you protect routes?" beforeLoad on a layout route, throwing redirect({ to: '/login' }). A pathless _auth folder protects many pages without changing URLs. Add: this guards the screen. The server must still verify the token.

"What does defaultPreload: 'intent' do?" Starts loading a route's code and data when the user hovers or touches its link, so the click feels instant.

"How does it work with TanStack Query?" Put queryClient in the router context. The loader calls ensureQueryData. The component calls useSuspenseQuery or useQuery with the same options. The loader gives the first render, the cache gives freshness.

One thing to volunteer: point out that the Register declaration is what ties the router type to the whole app, and that routeTree.gen.ts is generated and checked into git but never edited by hand.

Recall

  • TanStack Router makes routes typed. A typo in to, a missing params, or a wrong search value is a compile error.
  • File-based routes: __root.tsx (layout), index.tsx, products/index.tsx → /products, products/$productId.tsx → /products/:productId, _auth.tsx + _auth/account.tsx → /account (a pathless layout).
  • A tool (the Vite plugin, or npx tsr generate) writes routeTree.gen.ts. Never edit it by hand. declare module '@tanstack/react-router' { interface Register { router: typeof router } } makes the whole app typed.
  • Each file exports Route = createFileRoute('/path')({ component, loader, validateSearch, beforeLoad, pendingComponent, errorComponent, notFoundComponent }). Read data with Route.useLoaderData(), Route.useParams(), Route.useSearch().
  • validateSearch turns the raw URL search into a typed object, by hand or with Zod. Bad values become a fallback instead of a crash. A loader lists the search values it uses in loaderDeps.
  • Link: to, params={{ id }}, search={(prev) => ({ ...prev, x })}. useNavigate takes the same options. activeProps styles the current link.
  • beforeLoad runs before loaders. throw redirect({ to: '/login' }) guards a route. Real security stays on the server.
  • throw notFound() shows the route's notFoundComponent.
  • Context: createRootRouteWithContext<{ queryClient }>() and createRouter({ context }) give every loader the queryClient. Loader: ensureQueryData. Component: useSuspenseQuery.
  • defaultPreload: 'intent' preloads on hover or touch.

Self-test: What exactly is generated, and what does it let TypeScript do? · Why does params.productId have type string and not string | undefined? · Why does a loader need loaderDeps? · What does a folder named _auth do to URLs? · What is the job of the Register interface?

Next: 6.4.13 teaches Zod, the validation library you glimpsed in this page. It is the tool that turns "data from outside" (a URL, a form, a server reply) into data you can trust.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet