Overview
Search param validation ensures that URL query parameters match expected types and formats before they’re used in your application. TanStack Router supports multiple validation libraries through adapter packages.Supported Validation Libraries
TanStack Router provides official adapters for:- Zod -
@tanstack/zod-adapter - Valibot -
@tanstack/valibot-adapter - ArkType -
@tanstack/arktype-adapter
Using Zod Adapter
The Zod adapter provides integration with the popular Zod validation library.Installation
Basic Usage
Using Fallback Values
The Zod adapter provides afallback helper for providing default values when validation fails:
fallback function ensures that if validation fails, the specified fallback value is used instead of throwing an error.
Advanced Zod Options
ThezodValidator function accepts options to control input/output types:
Using Valibot Adapter
Valibot is a lightweight validation library with excellent TypeScript support.Installation
Basic Usage
Using Fallback Values
Using ArkType Adapter
ArkType provides ultra-fast runtime validation with concise syntax.Installation
Basic Usage
= operator:
Type Safety
All validation adapters provide full type safety. The validated search params are automatically typed:Accessing Search Params
There are multiple ways to access validated search params:In Components
With Selectors
In Loaders
In beforeLoad
Validation Errors
By default, validation errors will throw and can be caught by error boundaries. Use fallback values or optional fields to handle invalid params gracefully:Loader Dependencies
Combine search validation with loader dependencies to optimize data fetching:Custom Validation
You can also use plain functions for validation without an adapter:Creating Custom Adapters
You can create adapters for other validation libraries by implementing theValidatorAdapter interface:
types: TypeScript type information for input and outputparse: A function that validates and transforms the input
Best Practices
- Use fallback values for non-critical params to avoid validation errors
- Keep schemas simple - complex validation can impact performance
- Use optional fields for params that may not always be present
- Combine with loaderDeps to optimize data fetching
- Validate at the route level rather than in components for consistency
- Use enums for params with limited valid values
- Document expected formats in schema using
.describe()(Zod) or comments