Skip to main content
skill CX Codex

search-params — Claude Code skill: what it does, how to install

search-params equips agents with TanStack Router search param patterns: schema validation, inheritance across child routes, and URL middlewares.

MIT 228 installs ★ 15,341 updated 2026-10-25

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add TanStack/router --skill search-params -a claude-code
Open on GitHub

What search-params does

This skill guides coding agents through managing URL search parameters as JSON-first application state in tanstack-router version 1.171.15. It shows how to validate parameters using validateSearch with Zod, Valibot, or ArkType schemas. It also specifies how to read validated state inside components via Route.useSearch(), getRouteApi(), or loose useSearch({ strict: false }) calls.

Type inference is critical here. When combining Zod v3 with @tanstack/zod-adapter, using .catch() ruins TypeScript inference by turning output types into unknown. Developers must use fallback() instead. The skill also enforces leaving useSearch() returns unannotated.

For navigation, it provides syntax for keeping existing search keys with functional <Link> updates or useNavigate(). It covers middlewares like retainSearchParams to preserve query keys across routes, and stripSearchParams to drop defaults from the URL. Note that this sub-skill requires router-core.

What it helps with

  • Validate route search params with Zod, Valibot, or ArkType schemas
  • Read URL state using useSearch with inferred TypeScript types
  • Clean default values from URLs using stripSearchParams middleware
  • Share search parameters from parent routes to child views

Example prompts for the agent

  • Add search param validation for the catalog route using Zod and validateSearch
  • Keep the debug parameter active across page changes with retainSearchParams middleware
  • Build pagination with Link that increments page without clearing other search params

How to install search-params

1Skills CLI (Vercel)

npx skills add TanStack/router --skill search-params -a claude-code

2Manually: put the files in place

~/.claude/skills/search-params/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/search-params/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about search-params

How do I install search-params in Claude Code?

Run npx skills add TanStack/router --skill search-params -a claude-code in your terminal. The configuration is placed in ~/.claude/skills/search-params/SKILL.md.

What does the search-params skill do?

It provides TanStack Router search parameter conventions for AI agents. It instructs models on route validation schemas, inferred parameter access, and URL cleanup middlewares.

Does this skill have prerequisites?

Yes, it depends on the router-core skill. For Zod v3 setups, projects also need @tanstack/zod-adapter alongside zod.

Source text

SKILL.md · MIT
---
name: search-params
description: >-
  validateSearch, search param validation with Zod/Valibot/ArkType adapters,
  fallback(), search middlewares (retainSearchParams, stripSearchParams),
  custom serialization (parseSearch, stringifySearch), search param
  inheritance, loaderDeps for cache keys, reading and writing search params.
metadata:
  type: sub-skill
  library: tanstack-router
  library_version: '1.171.15'
requires:
  - router-core
sources:
  - TanStack/router:docs/router/guide/search-params.md
  - TanStack/router:docs/router/how-to/setup-basic-search-params.md
  - TanStack/router:docs/router/how-to/validate-search-params.md
  - TanStack/router:docs/router/how-to/navigate-with-search-params.md
  - TanStack/router:docs/router/how-to/share-search-params-across-routes.md
  - TanStack/router:docs/router/guide/custom-search-param-serialization.md
---

# Search Params

TanStack Router treats search params as JSON-first application state. They are automatically parsed from the URL into structured objects (numbers, booleans, arrays, nested objects) and validated via `validateSearch` on each route.

> **CRITICAL**: When using `zodValidator()` and Zod v3, use `fallback()` from `@tanstack/zod-adapter`, NOT zod's `.catch()`. Using `.catch()` with the zod adapter makes the output type `unknown`, destroying type safety. This does not apply to Valibot or ArkType (which use their own fallback mechanisms). It also does not apply to Zod v4, which should use `.catch()` and not use the `zodValidator()`.
> **CRITICAL**: Types are fully inferred. Never annotate the return of `useSearch()`.

## Setup: Zod Adapter (Recommended)

```bash
npm install zod @tanstack/zod-adapter
```

```tsx
// src/routes/products.tsx
import { createFileRoute } from '@tanstack/react-router'
import { z } from 'zod'

const productSearchSchema = z.object({
  page: z.number().default(1).catch(1),
  filter: z.string().default(''),
  sort: z.enum(['newest', 'oldest', 'price']).default('newest').catch('newest'),
})

export const Route = createFileRoute('/products')({
  validateSearch: productSearchSchema,
  component: ProductsPage,
})

function ProductsPage() {
  // page: number, filter: string, sort: 'newest' | 'oldest' | 'price'
  // ALL INFERRED — do not annotate
  const { page, filter, sort } = Route.useSearch()

  return (
    <div>
      <p>
        Page {page}, filter: {filter}, sort: {sort}
      </p>
    </div>
  )
}
```

## Reading Search Params

### In Route Components: `Route.useSearch()`

```tsx
function ProductsPage() {
  const { page, sort } = Route.useSearch()
  return <div>Page {page}</div>
}
```

### In Code-Split Components: `getRouteApi()`

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

const routeApi = getRouteApi('/products')

function ProductFilters() {
  const { sort } = routeApi.useSearch()
  return <select value={sort}>{/* options */}</select>
}
```

### From Any Component: `useSearch({ from })`

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

function SortIndicator() {
  const { sort } = useSearch({ from: '/products' })
  return <span>Sorted by: {sort}</span>
}
```

### Loose Access: `useSearch({ strict: false })`

```tsx
function GenericPaginator() {
  const search = useSearch({ strict: false })
  // search.page is number | undefined (union of all routes)
  return <span>Page: {search.page ?? 1}</span>
}
```

## Writing Search Params

### Link with Function Form (Preserves Existing Params)

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

function Pagination() {
  return (
    <Link
      from="/products"
      search={(prev) => ({ ...prev, page: prev.page + 1 })}
    >
      Next Page
    </Link>
  )
}
```

### Link with Object Form (Replaces All Params)

```tsx
<Link to="/products" search={{ page: 1, filter: '', sort: 'newest' }}>
  Reset
</Link>
```

### Programmatic: `useNavigate()`

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

function SortDropdown() {
  const navigate = useNavigate({ from: '/products' })

  return (
    <select
      onChange={(e) => {
        navigate({
          search: (prev) => ({ ...prev, sort: e.target.value, page: 1 }),
        })
      }}
    >
      <option value="newest">Newest</option>
      <option value="price">Price</option>
    </select>
  )
}
```

## Search Param Inheritance

Parent route search params are automatically merged into child routes:

```tsx
// src/routes/shop.tsx — parent defines shared params
import { createFileRoute } from '@tanstack/react-router'
import { z } from 'zod'

const shopSearchSchema = z.object({
  currency: z.enum(['USD', 'EUR']).default('USD').catch('USD'),
})

export const Route = createFileRoute('/shop')({
  validateSearch: shopSearchSchema,
})
```

```tsx
// src/routes/shop/products.tsx — child inherits currency
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/shop/products')({
  component: ShopProducts,
})

function ShopProducts() {
  // currency is available here from parent — fully typed
  const { currency } = Route.useSearch()
  return <div>Currency: {currency}</div>
}
```

## Search Middlewares

### `retainSearchParams` — Keep Params Across Navigation

```tsx
import { createRootRoute, retainSearchParams } from '@tanstack/react-router'
import { z } from 'zod'

const rootSearchSchema = z.object({
  debug: z.boolean().optional(),
})

export const Route = createRootRoute({
  validateSearch: rootSearchSchema,
  search: {
    middlewares: [retainSearchParams(['debug'])],
  },
})
```

### `stripSearchParams` — Remove Default Values from URL

```tsx
import { createFileRoute, stripSearchParams } from '@tanstack/react-router'
import { z } from 'zod'

const defaults = { sort: 'newest', page: 1 }

const searchSchema = z.object({
  sort: z.string().default(defaults.sort),
  page: z.number().default(defaults.page),
})

export const Route = createFileRoute('/items')({
  validateSearch: searchSchema,
  search: {
    middlewares: [stripSearchParams(defaults)],
  },
})
```

### Chaining Middlewares

```tsx
export const Route = createFileRoute('/search')({
  validateSearch: z.object({
    retainMe: z.string().optional(),
    arrayWithDefaults: z.string().array().default(['foo', 'bar']),
    required: z.string(),
  }),
  search: {
    middlewares: [
      retainSearchParams(['retainMe']),
      stripSearchParams({ arrayWithDefaults: ['foo', 'bar'] }),
    ],
  },
})
```

## Custom Serialization

Override the default JSON serialization at the router level:

```tsx
import {
  createRouter,
  parseSearchWith,
  stringifySearchWith,
} from '@tanstack/react-router'

const router = createRouter({
  routeTree,
  // Example: use JSURL2 for compact, human-readable URLs
  parseSearch: parseSearchWith(parse),
  stringifySearch: stringifySearchWith(stringify),
})
```

## Using Search Params in Loaders via `loaderDeps`

```tsx
export const Route = createFileRoute('/products')({
  validateSearch: productSearchSchema,
  // Pick ONLY the params the loader needs — not the entire search object
  loaderDeps: ({ search }) => ({ page: search.page }),
  loader: async ({ deps }) => {
    return fetchProducts({ page: deps.page })
  },
})
```

## Common Mistakes

### 1. HIGH: Using zod v3's `.catch()` with `zodValidator()` instead of adapter `fallback()`

```tsx
// WRONG — .catch() with zodValidator makes the type unknown
const schema = z.object({ page: z.number().catch(1) })
validateSearch: zodValidator(schema) // page is typed as unknown!

// CORRECT — fallback() preserves the inferred type
import { fallback } from '@tanstack/zod-adapter'
const schema = z.object({ page: fallback(z.number(), 1) })
```

**Important:** This only applies when using Zod v3, not when using Zod v4. For v4, using `.catch()` is correct.

### 2. HIGH: Returning entire search object from `loaderDeps`

```tsx
// WRONG — loader re-runs on ANY search param change
loaderDeps: ({ search }) => search

// CORRECT — loader only re-runs when page changes
loaderDeps: ({ search }) => ({ page: search.page })
```

### 3. HIGH: Passing Date objects in search params

```tsx
// WRONG — Date does not serialize correctly to JSON in URLs
<Link search={{ startDate: new Date() }}>

// CORRECT — convert to ISO string
<Link search={{ startDate: new Date().toISOString() }}>
```

### 4. MEDIUM: Parent route missing `validateSearch` blocks inheritance

```tsx
// WRONG — child cannot access shared params
export const Route = createRootRoute({
  component: RootComponent,
  // no validateSearch!
})

// CORRECT — parent must define validateSearch for children to inherit
export const Route = createRootRoute({
  validateSearch: globalSearchSchema,
  component: RootComponent,
})
```

### 5. HIGH (cross-skill): Using search as object instead of function loses params

```tsx
// WRONG — replaces ALL search params, losing any existing ones
<Link to="." search={{ page: 2 }}>Page 2</Link>

// CORRECT — preserves existing params, updates only page
<Link to="." search={(prev) => ({ ...prev, page: 2 })}>Page 2</Link>
```

## References

- [Validation Patterns Reference](./references/validation-patterns.md) — comprehensive patterns for all validation libraries

© TanStack · MIT · TanStack/router

Similar skills

All skills for Frontend and UI →

From the same set25

The whole set →
router-query router-query guides the integration of TanStack Router and TanStack Query, covering router context setup, loader prefetching, and SSR QueryClient isolation. CX Codex +1 448installs start-server-core start-server-core — a skill for Claude Code and five other platforms covering the TanStack Start server runtime: createStartHandler, request and response utilities, cookie management via AsyncLocalStorage. CX Codex +1 408installs router-plugin Configures the TanStack Router bundler plugin for route generation and code splitting. Works across Vite, Webpack, Rspack, and esbuild setups. CX Codex +1 374installs data-loading This skill covers data loading in TanStack Router, including cache keys, pending UI, errors, router context, and deferred results. CX Codex +1 230installs type-safety type-safety — a skill that teaches AI code generators to write type-safe TanStack Router code: never cast inferred values, register the module once, narrow types with from and getRouteApi, optimize TypeScript performance. CX Codex +1 223installs server-functions server-functions teaches your coding agent how to build type-safe RPCs in TanStack Start with createServerFn, validate inputs using Zod, and trigger mutations from UI components. CX Codex +1 221installs auth-and-guards auth-and-guards — a skill for protecting routes in TanStack Router. Redirects unauthenticated users, embeds role and permission checks, integrates Auth0, Clerk, Supabase via router context. CX Codex +1 219installs navigation This skill guides TanStack Router navigation with links, programmatic transitions, route preloading, and protection against leaving dirty forms. CX Codex +1 214installs

Project sponsors

Companies that keep this analytics open