0
# Router Creation & Configuration
1
2
Core router setup and configuration for creating type-safe routing instances with comprehensive options for data loading, caching, error handling, and SSR support.
3
4
## Capabilities
5
6
### Router Creation
7
8
Creates a new router instance with the specified route tree and configuration options.
9
10
```typescript { .api }
11
/**
12
* Create a router instance with route tree and configuration
13
* @param options - Router configuration options including route tree, history, and defaults
14
* @returns Router instance for use with RouterProvider
15
*/
16
function createRouter<TRouteTree extends AnyRoute>(
17
options: RouterConstructorOptions<TRouteTree>
18
): Router<TRouteTree>;
19
20
interface RouterConstructorOptions<TRouteTree extends AnyRoute> {
21
/** The route tree defining all application routes */
22
routeTree: TRouteTree;
23
/** History instance for navigation (defaults to createBrowserHistory()) */
24
history?: RouterHistory;
25
/** Base path for the router */
26
basepath?: string;
27
/** Router context shared across all routes */
28
context?: TRouterContext;
29
/** Default preload strategy for routes */
30
defaultPreload?: false | "intent" | "render" | "viewport";
31
/** Default preload delay in milliseconds */
32
defaultPreloadDelay?: number;
33
/** Default component used when route has no component */
34
defaultComponent?: RouteComponent;
35
/** Default error component for route errors */
36
defaultErrorComponent?: ErrorRouteComponent;
37
/** Default pending component shown during loading */
38
defaultPendingComponent?: RouteComponent;
39
/** Default not found component for 404 errors */
40
defaultNotFoundComponent?: NotFoundRouteComponent;
41
/** Minimum time to show pending component */
42
defaultPendingMinMs?: number;
43
/** Default time before showing pending component */
44
defaultPendingMs?: number;
45
/** Default stale time for route data */
46
defaultStaleTime?: number;
47
/** Default garbage collection time */
48
defaultGcTime?: number;
49
/** Whether routes are case sensitive */
50
caseSensitive?: boolean;
51
/** Trailing slash handling */
52
trailingSlash?: "always" | "never" | "preserve";
53
/** Enable structural sharing by default */
54
defaultStructuralSharing?: boolean;
55
/** Router wrapper component */
56
Wrap?: (props: { children: React.ReactNode }) => JSX.Element;
57
/** Inner router wrapper component */
58
InnerWrap?: (props: { children: React.ReactNode }) => JSX.Element;
59
/** Default error handler */
60
defaultOnCatch?: (error: Error, errorInfo: ErrorInfo) => void;
61
}
62
```
63
64
**Usage Examples:**
65
66
```typescript
67
import { createRouter, createBrowserHistory } from "@tanstack/react-router";
68
69
// Basic router creation
70
const router = createRouter({
71
routeTree,
72
});
73
74
// Router with custom configuration
75
const router = createRouter({
76
routeTree,
77
basepath: "/app",
78
defaultPreload: "intent",
79
defaultStaleTime: 5000,
80
caseSensitive: true,
81
trailingSlash: "never",
82
defaultComponent: () => <div>Loading...</div>,
83
defaultErrorComponent: ({ error }) => <div>Error: {error.message}</div>,
84
});
85
86
// Router with custom history
87
const customHistory = createBrowserHistory();
88
const router = createRouter({
89
routeTree,
90
history: customHistory,
91
context: {
92
user: { id: "123", name: "John" },
93
theme: "dark",
94
},
95
});
96
```
97
98
### Router Configuration
99
100
Creates a router configuration object for advanced scenarios.
101
102
```typescript { .api }
103
/**
104
* Create a router configuration object
105
* @param config - Router configuration
106
* @returns Router configuration object
107
*/
108
function createRouterConfig<TRouteTree extends AnyRoute>(
109
config: RouterConstructorOptions<TRouteTree>
110
): RouterConfig<TRouteTree>;
111
```
112
113
### Router Class
114
115
The main router class that manages navigation state, route matching, and lifecycle.
116
117
```typescript { .api }
118
class Router<TRouteTree extends AnyRoute = AnyRoute> {
119
/** Router history instance */
120
history: RouterHistory;
121
/** Current router state */
122
state: RouterState<TRouteTree>;
123
/** Route tree */
124
routeTree: TRouteTree;
125
/** Router options */
126
options: RouterOptions;
127
128
/**
129
* Navigate to a new location
130
* @param options - Navigation options
131
* @returns Promise that resolves when navigation completes
132
*/
133
navigate<TFrom extends RoutePaths<TRouteTree> = "/">(
134
options: NavigateOptions<TRouteTree, TFrom>
135
): Promise<void>;
136
137
/**
138
* Build a location object from navigation options
139
* @param options - Navigation options
140
* @returns Parsed location object
141
*/
142
buildLocation<TFrom extends RoutePaths<TRouteTree> = "/">(
143
options: BuildLocationOptions<TRouteTree, TFrom>
144
): ParsedLocation;
145
146
/**
147
* Invalidate all route matches
148
* @returns Promise that resolves when invalidation completes
149
*/
150
invalidate(): Promise<void>;
151
152
/**
153
* Load a route by location
154
* @param location - Location to load
155
* @returns Promise that resolves when loading completes
156
*/
157
load(location?: ParsedLocation): Promise<void>;
158
159
/**
160
* Preload a route
161
* @param options - Navigation options for route to preload
162
* @returns Promise that resolves when preloading completes
163
*/
164
preloadRoute<TFrom extends RoutePaths<TRouteTree> = "/">(
165
options: NavigateOptions<TRouteTree, TFrom>
166
): Promise<void>;
167
168
/**
169
* Subscribe to router state changes
170
* @param fn - Listener function
171
* @returns Unsubscribe function
172
*/
173
subscribe(fn: (state: RouterState<TRouteTree>) => void): () => void;
174
175
/**
176
* Match routes for a location
177
* @param location - Location to match
178
* @returns Array of route matches
179
*/
180
matchRoutes(location: ParsedLocation): RouteMatch[];
181
}
182
```
183
184
## Types
185
186
### Router State
187
188
```typescript { .api }
189
interface RouterState<TRouteTree extends AnyRoute = AnyRoute> {
190
/** Current location */
191
location: ParsedLocation;
192
/** Currently matched routes */
193
matches: RouteMatch[];
194
/** Pending matches during navigation */
195
pendingMatches?: RouteMatch[];
196
/** Whether router is in loading state */
197
isLoading: boolean;
198
/** Whether router is transitioning between routes */
199
isTransitioning: boolean;
200
/** Last updated timestamp */
201
lastUpdated: number;
202
/** Navigation status */
203
status: "idle" | "pending" | "success" | "error";
204
}
205
```
206
207
### Router Events
208
209
```typescript { .api }
210
interface RouterEvents {
211
onBeforeLoad: (event: {
212
router: Router;
213
fromLocation: ParsedLocation;
214
toLocation: ParsedLocation;
215
}) => void;
216
onLoad: (event: {
217
router: Router;
218
fromLocation: ParsedLocation;
219
toLocation: ParsedLocation;
220
}) => void;
221
onBeforeNavigate: (event: {
222
router: Router;
223
fromLocation: ParsedLocation;
224
toLocation: ParsedLocation;
225
}) => void;
226
onNavigate: (event: {
227
router: Router;
228
fromLocation: ParsedLocation;
229
toLocation: ParsedLocation;
230
}) => void;
231
}
232
```
233
234
### History Types
235
236
```typescript { .api }
237
interface RouterHistory {
238
/** Current location */
239
location: HistoryLocation;
240
/** Go back in history */
241
back(): void;
242
/** Go forward in history */
243
forward(): void;
244
/** Go to specific history entry */
245
go(n: number): void;
246
/** Push new location */
247
push(path: string, state?: any): void;
248
/** Replace current location */
249
replace(path: string, state?: any): void;
250
/** Create href for path */
251
createHref(path: string): string;
252
/** Subscribe to location changes */
253
subscribe(fn: (location: HistoryLocation) => void): () => void;
254
}
255
256
interface HistoryLocation {
257
pathname: string;
258
search: string;
259
hash: string;
260
state?: any;
261
key?: string;
262
}
263
```