|
| 1 | +--- |
| 2 | +id: persistSearchParams |
| 3 | +title: Search middleware to persist search params |
| 4 | +--- |
| 5 | + |
| 6 | +`persistSearchParams` is a search middleware that automatically saves and restores search parameters when navigating between routes. |
| 7 | + |
| 8 | +## persistSearchParams props |
| 9 | + |
| 10 | +`persistSearchParams` accepts one of the following inputs: |
| 11 | + |
| 12 | +- `undefined` (no arguments): persist all search params |
| 13 | +- a list of keys of those search params that shall be excluded from persistence |
| 14 | + |
| 15 | +## How it works |
| 16 | + |
| 17 | +The middleware has two main functions: |
| 18 | + |
| 19 | +1. **Saving**: Automatically saves search parameters when they change |
| 20 | +2. **Restoring**: Restores saved parameters when the middleware is triggered with empty search |
| 21 | + |
| 22 | +**Important**: The middleware only runs when search parameters are being processed. This means: |
| 23 | + |
| 24 | +- **Without search prop**: `<Link to="/users">` → Middleware doesn't run → No restoration |
| 25 | +- **With search function**: `<Link to="/users" search={(prev) => prev}>` → Middleware runs → Restoration happens |
| 26 | +- **With explicit search**: `<Link to="/users" search={{ name: 'John' }}>` → Middleware runs → No restoration (params provided) |
| 27 | + |
| 28 | +## Restoration Behavior |
| 29 | + |
| 30 | +⚠️ **Unexpected behavior warning**: If you use the persistence middleware but navigate without the `search` prop, the middleware will only trigger later when you modify search parameters. This can cause unexpected restoration of saved parameters mixed with your new changes. |
| 31 | + |
| 32 | +**Recommended**: Always be explicit about restoration intent using the `search` prop. |
| 33 | + |
| 34 | +## Examples |
| 35 | + |
| 36 | +```tsx |
| 37 | +import { z } from 'zod' |
| 38 | +import { createFileRoute, persistSearchParams } from '@tanstack/react-router' |
| 39 | + |
| 40 | +const usersSearchSchema = z.object({ |
| 41 | + name: z.string().optional().catch(''), |
| 42 | + status: z.enum(['active', 'inactive', 'all']).optional().catch('all'), |
| 43 | + page: z.number().optional().catch(0), |
| 44 | +}) |
| 45 | + |
| 46 | +export const Route = createFileRoute('/users')({ |
| 47 | + validateSearch: usersSearchSchema, |
| 48 | + search: { |
| 49 | + // persist all search params |
| 50 | + middlewares: [persistSearchParams()], |
| 51 | + }, |
| 52 | +}) |
| 53 | +``` |
| 54 | + |
| 55 | +```tsx |
| 56 | +import { z } from 'zod' |
| 57 | +import { createFileRoute, persistSearchParams } from '@tanstack/react-router' |
| 58 | + |
| 59 | +const productsSearchSchema = z.object({ |
| 60 | + category: z.string().optional(), |
| 61 | + minPrice: z.number().optional(), |
| 62 | + maxPrice: z.number().optional(), |
| 63 | + tempFilter: z.string().optional(), |
| 64 | +}) |
| 65 | + |
| 66 | +export const Route = createFileRoute('/products')({ |
| 67 | + validateSearch: productsSearchSchema, |
| 68 | + search: { |
| 69 | + // exclude tempFilter from persistence |
| 70 | + middlewares: [persistSearchParams(['tempFilter'])], |
| 71 | + }, |
| 72 | +}) |
| 73 | +``` |
| 74 | + |
| 75 | +```tsx |
| 76 | +import { z } from 'zod' |
| 77 | +import { createFileRoute, persistSearchParams } from '@tanstack/react-router' |
| 78 | + |
| 79 | +const searchSchema = z.object({ |
| 80 | + category: z.string().optional(), |
| 81 | + sortBy: z.string().optional(), |
| 82 | + sortOrder: z.string().optional(), |
| 83 | + tempFilter: z.string().optional(), |
| 84 | +}) |
| 85 | + |
| 86 | +export const Route = createFileRoute('/products')({ |
| 87 | + validateSearch: searchSchema, |
| 88 | + search: { |
| 89 | + // exclude tempFilter and sortBy from persistence |
| 90 | + middlewares: [persistSearchParams(['tempFilter', 'sortBy'])], |
| 91 | + }, |
| 92 | +}) |
| 93 | +``` |
| 94 | + |
| 95 | +## Restoration Patterns |
| 96 | + |
| 97 | +### Automatic Restoration with Links |
| 98 | + |
| 99 | +Use `search={(prev) => prev}` to trigger middleware restoration: |
| 100 | + |
| 101 | +```tsx |
| 102 | +import { Link } from '@tanstack/react-router' |
| 103 | + |
| 104 | +function Navigation() { |
| 105 | + return ( |
| 106 | + <div> |
| 107 | + {/* Full restoration - restores all saved parameters */} |
| 108 | + <Link to="/users" search={(prev) => prev}> |
| 109 | + Users |
| 110 | + </Link> |
| 111 | + |
| 112 | + {/* Partial override - restore saved params but override specific ones */} |
| 113 | + <Link to="/products" search={(prev) => ({ ...prev, category: 'Electronics' })}> |
| 114 | + Electronics Products |
| 115 | + </Link> |
| 116 | + |
| 117 | + {/* Clean navigation - no restoration */} |
| 118 | + <Link to="/users"> |
| 119 | + Users (clean slate) |
| 120 | + </Link> |
| 121 | + </div> |
| 122 | + ) |
| 123 | +} |
| 124 | +``` |
| 125 | + |
| 126 | +### Exclusion Strategies |
| 127 | + |
| 128 | +You have two ways to exclude parameters from persistence: |
| 129 | + |
| 130 | +**1. Middleware-level exclusion** (permanent): |
| 131 | +```tsx |
| 132 | +// These parameters are never saved |
| 133 | +middlewares: [persistSearchParams(['tempFilter', 'sortBy'])] |
| 134 | +``` |
| 135 | + |
| 136 | +**2. Link-level exclusion** (per navigation): |
| 137 | +```tsx |
| 138 | +// Restore saved params but exclude specific ones |
| 139 | +<Link to="/products" search={(prev) => { |
| 140 | + const { tempFilter, ...rest } = prev || {} |
| 141 | + return rest |
| 142 | +}}> |
| 143 | + Products (excluding temp filter) |
| 144 | +</Link> |
| 145 | +``` |
| 146 | + |
| 147 | +### Manual Restoration |
| 148 | + |
| 149 | +Access the store directly for full control: |
| 150 | + |
| 151 | +```tsx |
| 152 | +import { getSearchPersistenceStore, Link } from '@tanstack/react-router' |
| 153 | + |
| 154 | +function CustomNavigation() { |
| 155 | + const store = getSearchPersistenceStore() |
| 156 | + const savedUsersSearch = store.getSearch('/users') |
| 157 | + |
| 158 | + return ( |
| 159 | + <Link to="/users" search={savedUsersSearch || {}}> |
| 160 | + Users (with saved search) |
| 161 | + </Link> |
| 162 | + ) |
| 163 | +} |
| 164 | +``` |
| 165 | + |
| 166 | +## Using the search persistence store |
| 167 | + |
| 168 | +You can also access the search persistence store directly for manual control: |
| 169 | + |
| 170 | +```tsx |
| 171 | +import { getSearchPersistenceStore } from '@tanstack/react-router' |
| 172 | + |
| 173 | +// Get the fully typed store instance |
| 174 | +const store = getSearchPersistenceStore() |
| 175 | + |
| 176 | +// Get persisted search for a route |
| 177 | +const savedSearch = store.getSearch('/users') |
| 178 | + |
| 179 | +// Clear persisted search for a specific route |
| 180 | +store.clearSearch('/users') |
| 181 | + |
| 182 | +// Clear all persisted searches |
| 183 | +store.clearAllSearches() |
| 184 | + |
| 185 | +// Manually save search for a route |
| 186 | +store.saveSearch('/users', { name: 'John', status: 'active' }) |
| 187 | +``` |
| 188 | + |
| 189 | +```tsx |
| 190 | +import { getSearchPersistenceStore } from '@tanstack/react-router' |
| 191 | +import { useStore } from '@tanstack/react-store' |
| 192 | +import React from 'react' |
| 193 | + |
| 194 | +function MyComponent() { |
| 195 | + const store = getSearchPersistenceStore() |
| 196 | + const storeState = useStore(store.store) |
| 197 | + |
| 198 | + const clearUserSearch = () => { |
| 199 | + store.clearSearch('/users') |
| 200 | + } |
| 201 | + |
| 202 | + return ( |
| 203 | + <div> |
| 204 | + <p>Saved search: {JSON.stringify(storeState['/users'])}</p> |
| 205 | + <button onClick={clearUserSearch}>Clear saved search</button> |
| 206 | + </div> |
| 207 | + ) |
| 208 | +} |
| 209 | +``` |
0 commit comments