or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

data-loading.mderror-handling.mdindex.mdnavigation-links.mdpath-search-utils.mdreact-components.mdreact-hooks.mdroute-definition.mdrouter-creation.mdssr.md

route-definition.mddocs/

0

# Route Definition & Management

1

2

System for defining routes with type-safe parameters, search handling, data loading, and nested layouts. Supports both programmatic route creation and file-based routing patterns.

3

4

## Capabilities

5

6

### Route Creation

7

8

Create route instances with comprehensive configuration options including loaders, components, and validation.

9

10

```typescript { .api }

11

/**

12

* Create a route instance with configuration

13

* @param options - Route configuration options

14

* @returns Route instance

15

*/

16

function createRoute<TParentRoute extends AnyRoute = AnyRoute>(

17

options: RouteOptions<TParentRoute>

18

): Route<TParentRoute>;

19

20

interface RouteOptions<TParentRoute extends AnyRoute = AnyRoute> {

21

/** Function returning parent route */

22

getParentRoute?: () => TParentRoute;

23

/** Route path pattern */

24

path?: string;

25

/** Route ID for identification */

26

id?: string;

27

/** Route component */

28

component?: RouteComponent;

29

/** Error boundary component */

30

errorComponent?: ErrorRouteComponent;

31

/** Loading/pending component */

32

pendingComponent?: RouteComponent;

33

/** Not found component */

34

notFoundComponent?: NotFoundRouteComponent;

35

/** Route loader function */

36

loader?: RouteLoaderFn;

37

/** Route context function */

38

beforeLoad?: RouteContextFn;

39

/** Validation schema for search params */

40

validateSearch?: SearchValidator;

41

/** Transform search params */

42

search?: SearchTransform;

43

/** Static data */

44

staticData?: any;

45

/** Whether route should preload */

46

shouldReload?: boolean | ((match: RouteMatch) => boolean);

47

/** Stale time for route data */

48

staleTime?: number;

49

/** Garbage collection time */

50

gcTime?: number;

51

}

52

```

53

54

**Usage Examples:**

55

56

```typescript

57

import { createRoute, createRootRoute } from "@tanstack/react-router";

58

59

// Basic route

60

const homeRoute = createRoute({

61

getParentRoute: () => rootRoute,

62

path: "/",

63

component: () => <div>Home</div>,

64

});

65

66

// Route with parameters and loader

67

const postRoute = createRoute({

68

getParentRoute: () => rootRoute,

69

path: "/posts/$postId",

70

loader: async ({ params }) => {

71

const post = await fetchPost(params.postId);

72

return { post };

73

},

74

component: ({ useLoaderData }) => {

75

const { post } = useLoaderData();

76

return <div>{post.title}</div>;

77

},

78

});

79

80

// Route with search validation

81

const searchRoute = createRoute({

82

getParentRoute: () => rootRoute,

83

path: "/search",

84

validateSearch: (search) => ({

85

q: search.q || "",

86

page: Number(search.page) || 1,

87

}),

88

component: ({ useSearch }) => {

89

const { q, page } = useSearch();

90

return <SearchResults query={q} page={page} />;

91

},

92

});

93

```

94

95

### Root Route Creation

96

97

Create the root route that serves as the top-level route for the application.

98

99

```typescript { .api }

100

/**

101

* Create a root route

102

* @param options - Root route configuration options

103

* @returns Root route instance

104

*/

105

function createRootRoute<TRouterContext = unknown>(

106

options?: RootRouteOptions<TRouterContext>

107

): RootRoute<TRouterContext>;

108

109

/**

110

* Create a root route with typed context

111

* @returns Function to create root route with context

112

*/

113

function createRootRouteWithContext<TRouterContext>(): <TRouter extends AnyRouter = AnyRouter>(

114

options?: RootRouteOptions<TRouterContext>

115

) => RootRoute<TRouterContext>;

116

117

interface RootRouteOptions<TRouterContext = unknown> {

118

/** Root component */

119

component?: RouteComponent;

120

/** Root error component */

121

errorComponent?: ErrorRouteComponent;

122

/** Root pending component */

123

pendingComponent?: RouteComponent;

124

/** Root not found component */

125

notFoundComponent?: NotFoundRouteComponent;

126

/** Root loader function */

127

loader?: (opts: { context: TRouterContext }) => any;

128

/** Root context function */

129

beforeLoad?: (opts: { context: TRouterContext }) => any;

130

}

131

```

132

133

**Usage Examples:**

134

135

```typescript

136

import { createRootRoute, createRootRouteWithContext, Outlet } from "@tanstack/react-router";

137

138

// Basic root route

139

const rootRoute = createRootRoute({

140

component: () => (

141

<div>

142

<nav>Navigation</nav>

143

<Outlet />

144

</div>

145

),

146

});

147

148

// Root route with typed context

149

const createRootWithContext = createRootRouteWithContext<{

150

user: User;

151

theme: "light" | "dark";

152

}>();

153

154

const rootRoute = createRootWithContext({

155

component: () => <App />,

156

beforeLoad: ({ context }) => {

157

console.log("User:", context.user);

158

return { ...context };

159

},

160

});

161

```

162

163

### File-Based Routes

164

165

Create routes based on file system conventions with automatic type generation and file-system-based routing patterns.

166

167

```typescript { .api }

168

/**

169

* Create a file-based route with automatic type inference

170

* @param path - File path for type inference

171

* @returns Function to create route with file-based typing

172

*/

173

function createFileRoute<TFilePath extends keyof FileRoutesByPath>(

174

path?: TFilePath

175

): FileRoute<TFilePath>['createRoute'];

176

177

/**

178

* Create a lazy file route for code splitting

179

* @param id - File path used as route ID

180

* @returns Function to create lazy file route

181

*/

182

function createLazyFileRoute<TFilePath extends keyof FileRoutesByPath>(

183

id: TFilePath

184

): (opts: LazyRouteOptions) => LazyRoute<FileRoutesByPath[TFilePath]['preLoaderRoute']>;

185

186

/**

187

* File route loader function (deprecated - use loader in createFileRoute options)

188

* @param path - File path

189

* @returns Function to define typed loader

190

*/

191

function FileRouteLoader<TFilePath extends keyof FileRoutesByPath>(

192

path: TFilePath

193

): <TLoaderFn>(loaderFn: TLoaderFn) => TLoaderFn;

194

```

195

196

### File Route Class

197

198

File route class for programmatic file-based route creation (deprecated in favor of createFileRoute).

199

200

```typescript { .api }

201

/**

202

* File route class (deprecated - use createFileRoute instead)

203

* @deprecated Use createFileRoute('/path/to/file')(options) instead

204

*/

205

class FileRoute<

206

TFilePath extends keyof FileRoutesByPath,

207

TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'],

208

TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'],

209

TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'],

210

TFullPath extends RouteConstraints['TFullPath'] = FileRoutesByPath[TFilePath]['fullPath']

211

> {

212

/** File path */

213

path?: TFilePath;

214

/** Silent mode flag */

215

silent?: boolean;

216

217

constructor(path?: TFilePath, opts?: { silent: boolean });

218

219

/**

220

* Create route from file route instance

221

* @param options - File route options

222

* @returns Route instance

223

*/

224

createRoute<TOptions extends FileBaseRouteOptions>(

225

options?: TOptions

226

): Route<TParentRoute, TPath, TFullPath, TFilePath, TId>;

227

}

228

```

229

230

**Usage Examples:**

231

232

```typescript

233

// In routes/index.tsx

234

export const Route = createFileRoute("/")({

235

component: Index,

236

});

237

238

function Index() {

239

return <div>Home</div>;

240

}

241

242

// In routes/posts/$postId.tsx

243

export const Route = createFileRoute("/posts/$postId")({

244

loader: ({ params }) => fetchPost(params.postId),

245

component: PostDetail,

246

});

247

248

// Lazy file route

249

export const Route = createLazyFileRoute("/posts/$postId")({

250

component: LazyPostDetail,

251

});

252

```

253

254

### Lazy Routes

255

256

Create routes that load components dynamically for code splitting with typed hook access.

257

258

```typescript { .api }

259

/**

260

* Create a lazy route for code splitting

261

* @param id - Route ID

262

* @returns Function to create lazy route

263

*/

264

function createLazyRoute<

265

TRouter extends AnyRouter = RegisteredRouter,

266

TId extends string = string,

267

TRoute extends AnyRoute = RouteById<TRouter['routeTree'], TId>

268

>(

269

id: ConstrainLiteral<TId, RouteIds<TRouter['routeTree']>>

270

): (opts: LazyRouteOptions) => LazyRoute<TRoute>;

271

272

interface LazyRouteOptions {

273

/** Lazy route component */

274

component?: LazyRouteComponent;

275

/** Lazy error component */

276

errorComponent?: ErrorRouteComponent;

277

/** Lazy pending component */

278

pendingComponent?: RouteComponent;

279

/** Lazy not found component */

280

notFoundComponent?: NotFoundRouteComponent;

281

}

282

```

283

284

### Lazy Route Class

285

286

Lazy route class with typed hooks for accessing route data.

287

288

```typescript { .api }

289

/**

290

* Lazy route class with typed hook access

291

*/

292

class LazyRoute<TRoute extends AnyRoute> {

293

/** Lazy route options including ID */

294

options: { id: string } & LazyRouteOptions;

295

296

constructor(opts: { id: string } & LazyRouteOptions);

297

298

/**

299

* Access match data for this lazy route

300

* @param opts - Match selection options

301

* @returns Route match data

302

*/

303

useMatch: UseMatchRoute<TRoute['id']>;

304

305

/**

306

* Access route context for this lazy route

307

* @param opts - Context selection options

308

* @returns Route context

309

*/

310

useRouteContext: UseRouteContextRoute<TRoute['id']>;

311

312

/**

313

* Access search params for this lazy route

314

* @param opts - Search selection options

315

* @returns Search parameters

316

*/

317

useSearch: UseSearchRoute<TRoute['id']>;

318

319

/**

320

* Access route params for this lazy route

321

* @param opts - Params selection options

322

* @returns Route parameters

323

*/

324

useParams: UseParamsRoute<TRoute['id']>;

325

326

/**

327

* Access loader dependencies for this lazy route

328

* @param opts - Loader deps selection options

329

* @returns Loader dependencies

330

*/

331

useLoaderDeps: UseLoaderDepsRoute<TRoute['id']>;

332

333

/**

334

* Access loader data for this lazy route

335

* @param opts - Loader data selection options

336

* @returns Loader data

337

*/

338

useLoaderData: UseLoaderDataRoute<TRoute['id']>;

339

340

/**

341

* Access navigation function for this lazy route

342

* @returns Typed navigation function

343

*/

344

useNavigate: () => UseNavigateResult<TRoute['fullPath']>;

345

}

346

```

347

348

### Route API

349

350

Access typed API for specific routes with helper methods.

351

352

```typescript { .api }

353

/**

354

* Get typed route API for a specific route

355

* @param id - Route ID

356

* @returns RouteApi instance

357

*/

358

function getRouteApi<TId extends string, TRouter extends AnyRouter = RegisteredRouter>(

359

id: TId

360

): RouteApi<TRouter, TId>;

361

362

class RouteApi<TRouter extends AnyRouter, TId extends RouteIds<TRouter>> {

363

/** Route ID */

364

id: TId;

365

366

/**

367

* Use loader data for this route

368

* @param opts - Options

369

* @returns Loader data

370

*/

371

useLoaderData<TSelected = ResolveLoaderData<TRouter, TId>>(

372

opts?: {

373

select?: (data: ResolveLoaderData<TRouter, TId>) => TSelected;

374

}

375

): TSelected;

376

377

/**

378

* Use route context

379

* @param opts - Options

380

* @returns Route context

381

*/

382

useRouteContext<TSelected = RouteContext<TRouter, TId>>(

383

opts?: {

384

select?: (context: RouteContext<TRouter, TId>) => TSelected;

385

}

386

): TSelected;

387

388

/**

389

* Use search params for this route

390

* @param opts - Options

391

* @returns Search params

392

*/

393

useSearch<TSelected = InferFullSearchSchema<TRouter, TId>>(

394

opts?: {

395

select?: (search: InferFullSearchSchema<TRouter, TId>) => TSelected;

396

}

397

): TSelected;

398

399

/**

400

* Use params for this route

401

* @param opts - Options

402

* @returns Route params

403

*/

404

useParams<TSelected = ResolveParams<TRouter, TId>>(

405

opts?: {

406

select?: (params: ResolveParams<TRouter, TId>) => TSelected;

407

}

408

): TSelected;

409

}

410

```

411

412

### Route Masking

413

414

Create route masks for URL masking and aliasing.

415

416

```typescript { .api }

417

/**

418

* Create a route mask for URL masking

419

* @param options - Masking options

420

* @returns Route mask configuration

421

*/

422

function createRouteMask<TRouteTree extends AnyRoute, TFrom extends string, TTo extends string>(

423

options: {

424

routeTree: TRouteTree;

425

from: TFrom;

426

to: TTo;

427

params?: Record<string, any>;

428

search?: Record<string, any>;

429

hash?: string;

430

unmaskOnReload?: boolean;

431

}

432

): RouteMask;

433

```

434

435

## Types

436

437

### Route Types

438

439

```typescript { .api }

440

interface Route<TParentRoute extends AnyRoute = AnyRoute> {

441

/** Route ID */

442

id: string;

443

/** Route path pattern */

444

path: string;

445

/** Full resolved path */

446

fullPath: string;

447

/** Parent route */

448

parentRoute?: TParentRoute;

449

/** Child routes */

450

children?: AnyRoute[];

451

/** Route options */

452

options: RouteOptions;

453

/** Add child routes */

454

addChildren<TChildren extends AnyRoute[]>(children: TChildren): RouteWithChildren<TChildren>;

455

}

456

457

interface RootRoute<TRouterContext = unknown> extends Route {

458

/** Root route marker */

459

isRoot: true;

460

/** Router context */

461

context?: TRouterContext;

462

}

463

```

464

465

### Route Match Types

466

467

```typescript { .api }

468

interface RouteMatch {

469

/** Match ID */

470

id: string;

471

/** Route ID this match represents */

472

routeId: string;

473

/** Pathname portion */

474

pathname: string;

475

/** Route parameters */

476

params: Record<string, any>;

477

/** Search parameters */

478

search: Record<string, any>;

479

/** Loader data */

480

loaderData?: any;

481

/** Route context */

482

context: RouteContext;

483

/** Match status */

484

status: "pending" | "success" | "error" | "idle";

485

/** Whether match is invalid */

486

invalid: boolean;

487

/** Error if any */

488

error?: unknown;

489

/** Updated timestamp */

490

updatedAt: number;

491

}

492

```

493

494

### Component Types

495

496

```typescript { .api }

497

type RouteComponent = React.ComponentType<{

498

useParams: () => any;

499

useSearch: () => any;

500

useLoaderData: () => any;

501

useRouteContext: () => any;

502

useNavigate: () => any;

503

}>;

504

505

type ErrorRouteComponent = React.ComponentType<{

506

error: Error;

507

info: { componentStack: string };

508

reset: () => void;

509

}>;

510

511

type NotFoundRouteComponent = React.ComponentType<{

512

data?: any;

513

}>;

514

```

515

516

### Loader Types

517

518

```typescript { .api }

519

type RouteLoaderFn<TRoute extends AnyRoute = AnyRoute> = (

520

context: LoaderFnContext<TRoute>

521

) => any | Promise<any>;

522

523

interface LoaderFnContext<TRoute extends AnyRoute = AnyRoute> {

524

/** Route parameters */

525

params: ResolveParams<TRoute>;

526

/** Search parameters */

527

search: InferFullSearchSchema<TRoute>;

528

/** Route context */

529

context: RouteContext<TRoute>;

530

/** Location object */

531

location: ParsedLocation;

532

/** Abort signal */

533

signal: AbortSignal;

534

}

535

```