Course contentsShow
← React
Lesson 1879 of 2,39643. RoutingFree lesson

Search Params with Validation and Parsing

Use validateSearch to define typed, validated search parameters with automatic parsing and encoding.

Search Params with Validation and Parsing

What you'll learn: How to use validateSearch in TanStack Router to define typed, validated search parameters that parse and encode automatically.

Why Raw Search Params Aren't Enough

In React Router, you manually parse search params as strings and handle conversion yourself. TanStack Router takes a different approach: you define the shape and validation rules upfront, and the router handles parsing, encoding, and type safety automatically.

Think of it like a contract: instead of accepting any random query string and hoping it's valid, you declare exactly what parameters you expect, what types they should be, and what defaults to use.

The validateSearch Function

When defining a route with createRoute, you can provide a validateSearch function. This function receives the raw search params object and returns a typed, validated version:

import { createRoute } from '@tanstack/react-router';

const productRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/products',
  validateSearch: (search: Record<string, unknown>) => {
    return {
      page: Number(search.page ?? 1),
      sort: (search.sort as string) ?? 'name',
      minPrice: search.minPrice ? Number(search.minPrice) : undefined,
    };
  },
});

Now when you access search params in this route, TypeScript knows the exact shape, and values are already parsed from strings to their proper types.

Automatic Encoding

When you navigate and set search params, TanStack Router encodes them back to URL strings automatically. You work with numbers and booleans in your code; the router handles the string conversion behind the scenes.

Key Takeaway: validateSearch transforms TanStack Router search params from loose strings into strongly-typed, validated objects with automatic parsing and encoding, eliminating manual conversion boilerplate and runtime errors.