### Migration Example
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/DOCUMENTATION_SUMMARY.txt
Provides an example of how to migrate from a standard React Router setup to using typesafe routes. This helps in understanding the transition process and required code changes.
```typescript
// Before:
// } />
// After:
const userRoute = createRoute({
path: "/users/:userId",
types: {
params: z.object({ userId: z.string() })
},
component: UserPage
});
// ... then use renderRoutes(routes)
```
--------------------------------
### Install react-router-typesafe-routes
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/README.md
Install the library using yarn. Ensure react and react-router are installed as peer dependencies.
```bash
yarn add react-router-typesafe-routes
```
--------------------------------
### Example: Standard Schema Route Configuration
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/configuration.md
Demonstrates configuring the schema type helper with ArkType validators for route parameters.
```typescript
import { configure, schema, parser } from "react-router-typesafe-routes/standard-schema";
import { type } from "arktype";
const { schema: customSchema } = configure({
parserFactory: parser
});
const myRoute = route({
params: { id: customSchema(type("string.uuid"), parser("string")) }
});
```
--------------------------------
### Example: Yup Route Configuration
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/configuration.md
Demonstrates configuring the yup type helper with Yup validators for route parameters.
```typescript
import { configure, yup, parser } from "react-router-typesafe-routes/yup";
import { string as yupString } from "yup";
const { yup: customYup } = configure({
parserFactory: parser
});
const myRoute = route({
params: { email: customYup(yupString().email()) }
});
```
--------------------------------
### Example: Zod Route Configuration
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/configuration.md
Demonstrates configuring the zod type helper with Zod validators for route parameters.
```typescript
import { configure, zod, parser } from "react-router-typesafe-routes/zod";
import { z } from "zod";
const { zod: customZod } = configure({
parserFactory: parser
});
const myRoute = route({
params: { id: customZod(z.string().uuid()) }
});
```
--------------------------------
### State Navigation Example
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/DOCUMENTATION_SUMMARY.txt
Provides an example of navigating with state using the `useNavigate` hook. State can be used to pass transient data between routes without affecting the URL.
```typescript
navigate(someRoute, {
state: { message: "Welcome back!" },
replace: true
});
```
--------------------------------
### Link and Navigation Examples
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/DOCUMENTATION_SUMMARY.txt
Shows how to use the `Link` component and `useNavigate` hook for type-safe navigation. This ensures that navigation targets and parameters are correctly typed.
```typescript
User 123
const navigate = useNavigate();
navigate(userRoute, { params: { userId: "456" } });
```
--------------------------------
### ArkType Validation Example
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/validation-libraries.md
Example of defining routes with parameters and search parameters validated by ArkType using Standard Schema.
```typescript
import { route } from "react-router-typesafe-routes";
import { schema, parser } from "react-router-typesafe-routes/standard-schema";
import { type } from "arktype";
const userRoute = route({
path: "user/:id",
params: {
id: schema(type("string.uuid"), parser("string"))
},
searchParams: {
email: schema(type("string.email"), parser("string")),
age: schema(type("number > 0"), parser("number"))
}
});
```
--------------------------------
### React Router Integration
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/DOCUMENTATION_SUMMARY.txt
Provides an example of integrating typesafe routes with React Router's `Routes` and `Route` components. This setup allows React Router to render the correct components based on the defined typesafe routes.
```typescript
const routes = [
createRoute({ path: "/", component: HomePage }),
userRoute
];
{renderRoutes(routes)}
```
--------------------------------
### Custom Parser Implementation
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/configuration.md
Example of a custom parser object with stringify and parse methods. It demonstrates accessing the parser context, including hint and kind.
```typescript
const customParser: Parser = {
stringify(value, { hint, kind }) {
// hint: "string" | "number" | "boolean" | "date" | undefined
// kind: "pathname" | "search" | "hash"
},
parse(value, { hint, kind }) {
// Same hint and kind values
}
};
```
--------------------------------
### Type Composition Example
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/README.md
Shows how pathless routes can be composed to share type definitions, allowing multiple routes to inherit the same search parameter types.
```typescript
const pagination = route({
searchParams: { page: number(), pageSize: number() }
});
const route1 = route({
path: "items",
compose: [pagination] // Inherits pagination types
});
```
--------------------------------
### Custom Standard Schema Implementation Example
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/validation-libraries.md
Demonstrates defining a route with a custom validator object that adheres to the Standard Schema specification.
```typescript
import { schema } from "react-router-typesafe-routes/standard-schema";
// Any library implementing the Standard Schema spec
const myValidator = {
"~standard": {
validate: (value) => {
if (typeof value !== "string") {
return { issues: [{ message: "Must be string" }] };
}
return { value };
}
}
};
const route = route({
params: {
name: schema(myValidator, parser("string"))
}
});
```
--------------------------------
### Route Inheritance Example
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/README.md
Demonstrates how child routes inherit search parameters from parent routes. Explicit child types override parent types.
```typescript
const parent = route({
searchParams: { page: number() }
});
const child = route({
path: "details",
searchParams: { tab: string() } // Adds to parent
});
// child now has both: page and tab
```
--------------------------------
### Usage Examples for number() Helper
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/api-type-helpers.md
Demonstrates various ways to use the number() helper, including basic number types, custom integer and range validators, default values, and array types for route parameters and search parameters.
```typescript
import { route, number } from "react-router-typesafe-routes";
// Basic number
const route1 = route({
params: { id: number() }
});
// Integer validator
const integer = (value: number) => {
if (!Number.isInteger(value)) {
throw new Error("Must be an integer");
}
return value;
};
// Number in specific range
const percentValidator = (value: number) => {
if (value < 0 || value > 100) {
throw new Error("Must be 0-100");
}
return value;
};
const route2 = route({
searchParams: {
page: number(integer),
confidence: number(percentValidator)
}
});
// Number with default
const route3 = route({
searchParams: {
limit: number().default(20)
}
});
// Array of numbers
const route4 = route({
searchParams: {
ids: number().array()
}
});
```
--------------------------------
### Usage Example of useTypedSearchParams
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/api-hooks.md
Demonstrates how to use the useTypedSearchParams hook to retrieve and update typed search parameters within a React component. Includes examples for setting new values, updating via a function, passing state, and preserving untyped parameters.
```typescript
import { route, string, number } from "react-router-typesafe-routes";
import { useTypedSearchParams } from "react-router-typesafe-routes";
const listRoute = route({
path: "items",
searchParams: {
page: number(),
filter: string()
}
});
function ItemList() {
const [searchParams, setSearchParams] = useTypedSearchParams(listRoute);
return (
Page: {searchParams.page || 1}
Filter: {searchParams.filter}
{/* Update with new values */}
{/* Update using function */}
{/* With state */}
{/* Preserve untyped params */}
);
}
```
--------------------------------
### Configure Global Parser
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/configuration.md
Use the `configure` function with a `parserFactory` to set a custom parser for all type helpers. This example uses the default JSON-based parser.
```typescript
import { configure, parser } from "react-router-typesafe-routes";
// Use default parser (JSON-based)
const { type, string, number } = configure({
parserFactory: parser
});
// All these will use the default JSON parser
const myRoute = route({
params: { id: number() },
searchParams: { query: string() }
});
```
--------------------------------
### Built-in Parser Usage Examples
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/configuration.md
Demonstrates how to use the built-in parser for string, date, and JSON serialization. String serialization passes values as-is, date serialization uses ISO 8601 format, and JSON serialization handles complex objects.
```typescript
import { parser } from "react-router-typesafe-routes";
// String serialization (no quotes)
const stringParser = parser("string");
// "hello" → "hello" (not '"hello"')
// Date serialization (ISO format)
const dateParser = parser("date");
// new Date("2025-06-27") → "2025-06-27T00:00:00.000Z"
// JSON serialization (default)
const jsonParser = parser();
// { x: 1 } → "{\"x\":1}"
```
--------------------------------
### Custom Entity Parser Implementation
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/configuration.md
Provides an example of a custom parser that handles an 'entity' hint for custom serialization and deserialization of objects with an 'id' property, falling back to the built-in parser for other hints.
```typescript
import { Parser, ParserContext, ParserHint, parser } from "react-router-typesafe-routes";
type CustomParserHint = ParserHint | "entity";
type CustomParserType =
T extends "entity" ? { id: number } : ParserType>;
function customParser(
defaultHint?: T
): Parser, CustomParserHint> {
return {
stringify(value, { hint, kind }) {
const resolvedHint = hint ?? defaultHint;
if (resolvedHint === "entity") {
// Custom serialization for entities
return JSON.stringify((value as any).id);
}
// Fall back to built-in parser
const builtIn = parser();
return builtIn.stringify(value, { hint: resolvedHint as ParserHint, kind });
},
parse(value, { hint, kind }) {
const resolvedHint = hint ?? defaultHint;
if (resolvedHint === "entity") {
// Custom deserialization for entities
const id = JSON.parse(value);
return { id };
}
// Fall back to built-in parser
const builtIn = parser();
return builtIn.parse(value, { hint: resolvedHint as ParserHint, kind });
}
};
}
// Use custom parser
const myRoute = route({
params: { entity: type(entityValidator, customParser("entity")) }
});
```
--------------------------------
### Import Standard Schema Configuration
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/configuration.md
Import the `configure` function and `schema` type helper from the standard schema entry point.
```typescript
import { configure, schema } from "react-router-typesafe-routes/standard-schema";
```
--------------------------------
### ParserHint Type
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/types.md
A type alias for hints that guide the behavior of parsers, specifying how values should be serialized or deserialized.
```APIDOC
### ParserHint Type
```typescript
type ParserHint = "string" | "number" | "boolean" | "date" | "unknown";
```
Hints guide parser behavior:
- `"string"`: No wrapping quotes in serialization
- `"number"`, `"boolean"`: JSON serialization
- `"date"`: ISO 8601 string serialization
- `"unknown"`: JSON serialization (default)
```
--------------------------------
### configure()
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/api-type-helpers.md
Sets a custom parser factory globally for all type helpers in an entry point.
```APIDOC
## configure()
### Description
Sets a custom parser factory globally for all type helpers in an entry point.
### Function Signature
```typescript
function configure(options: {
parserFactory: (hint: ParserHint) => Parser
}): {
type: typeof type,
string: typeof string,
number: typeof number,
boolean: typeof boolean,
date: typeof date,
union: typeof union
}
```
### Parameters
#### Path Parameters
- **options.parserFactory** (Function) - Required - Factory function that returns a parser given a hint
### Return Type
Returns an object with all type helpers (`type`, `string`, `number`, `boolean`, `date`, `union`) using the custom parser factory.
### Usage Example
```typescript
import { configure, parser } from "react-router-typesafe-routes";
// Custom parser factory
const customParserFactory = (hint) => {
return parser(hint);
};
const { type, string, number, boolean } = configure({
parserFactory: customParserFactory
});
// Now all these helpers use the custom parser
const myRoute = route({
params: { id: number() }
});
```
```
--------------------------------
### Route with search params and hash
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/api-route.md
Illustrates how to define a route with typed search parameters and a hash, and then build a URL with these components.
```APIDOC
## Route with search params and hash
### Description
Shows how to define a route that includes typed search parameters and a hash, and then construct a URL incorporating these elements.
### Method
N/A (Code examples for library usage)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```typescript
import { route, string, number, union } from "react-router-typesafe-routes";
const listRoute = route({
path: "items",
searchParams: {
page: number(),
filter: string()
},
hash: union(["grid", "list"])
});
const url = listRoute.$buildPath({
searchParams: { page: 2, filter: "active" },
hash: "grid"
});
// Returns: "/items?page=2&filter=active#grid"
```
### Response
N/A
```
--------------------------------
### Global Configuration
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/DOCUMENTATION_SUMMARY.txt
The `configure()` function allows for setting up global parser configurations, influencing how all routes within the application handle parsing and validation.
```APIDOC
## configure()
### Description
Sets up global parser configurations for the entire application. This function influences how route parameters, search parameters, hash fragments, and navigation state are parsed and validated across all defined routes.
### Usage
Call `configure()` at the entry point of your application to establish default parsing and validation behaviors. It can accept a `Configuration` object to customize settings.
```
--------------------------------
### Import Yup Configuration
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/configuration.md
Import the `configure` function and `yup` type helper from the Yup entry point.
```typescript
import { configure, yup } from "react-router-typesafe-routes/yup";
```
--------------------------------
### Standard Schema Validation Integration
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/quick-reference.md
Use Standard Schema for validation, which requires explicit parser hints. Ensure 'arktype' is installed and imported.
```typescript
import { schema, parser } from "react-router-typesafe-routes/standard-schema";
import { type } from "arktype";
// Must specify parser hint explicitly
schema(type("string"), parser("string"))
schema(type("string.email"), parser("string"))
schema(type("number > 0"), parser("number"))
```
--------------------------------
### Import configure and parser
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/configuration.md
Import the necessary functions `configure` and `parser` from the library.
```typescript
import { configure, parser } from "react-router-typesafe-routes";
```
--------------------------------
### Integrate Third-Party Validation with Yup
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/README.md
Use the yup integration to define route parameters with Yup schemas for validation. Ensure Yup is installed and imported.
```typescript
// Yup
import { yup } from "react-router-typesafe-routes/yup";
import { string } from "yup";
const route = route({
params: { email: yup(string().email()) }
});
```
--------------------------------
### Import Zod Configuration
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/configuration.md
Import the `configure` function and `zod` type helper from the Zod entry point.
```typescript
import { configure, zod } from "react-router-typesafe-routes/zod";
```
--------------------------------
### Integrate Third-Party Validation with Zod
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/README.md
Use the zod integration to define route parameters with Zod schemas for validation. Ensure Zod is installed and imported.
```typescript
// Zod
import { zod } from "react-router-typesafe-routes/zod";
import { z } from "zod";
const route = route({
params: { id: zod(z.string().uuid()) }
});
```
--------------------------------
### Basic String Type Usage
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/api-type-helpers.md
Demonstrates how to use the basic string() helper for a 'name' search parameter.
```typescript
import { route, string } from "react-router-typesafe-routes";
// Basic string
const route1 = route({
searchParams: { name: string() }
});
```
--------------------------------
### Basic pathname route with typed params
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/api-route.md
Demonstrates defining a route with typed path parameters and building paths for both the parent and nested routes.
```APIDOC
## Basic pathname route with typed params
### Description
Defines a route with typed path parameters and shows how to build paths for the parent route and a nested route, including the parent's parameters.
### Method
N/A (Code examples for library usage)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```typescript
import { route, number, string } from "react-router-typesafe-routes";
const userRoute = route({
path: "user/:userId",
params: { userId: number() },
children: {
post: route({
path: "post/:postId?",
params: { postId: string() }
})
}
});
// Build a path
const path = userRoute.$buildPath({
params: { userId: 123 },
});
// Returns: "/user/123"
const pathWithPost = userRoute.post.$buildPath({
params: { userId: 123, postId: "abc" },
});
// Returns: "/user/123/post/abc"
```
### Response
N/A
```
--------------------------------
### Define Route with Multiple Search Parameters
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/patterns-and-examples.md
Illustrates defining a route with multiple typed search parameters and how to build URLs and use them in a component.
```typescript
import { route, string, number } from "react-router-typesafe-routes";
const listRoute = route({
path: "items",
searchParams: {
page: number(),
pageSize: number(),
query: string(),
sort: string()
}
});
// Build with search params
const url = listRoute.$buildPath({
searchParams: {
page: 2,
pageSize: 25,
query: "react",
sort: "date"
}
});
// → "/items?page=2&pageSize=25&query=react&sort=date"
// Use in component
function ItemsList() {
const [params, setParams] = useTypedSearchParams(listRoute);
return (
Page {params.page || 1}
Query: {params.query}
);
}
```
--------------------------------
### Yup Validation Integration
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/quick-reference.md
Integrate Yup schemas for type-safe validation. Yup must be installed and imported. Basic types and complex schemas with validation are supported.
```typescript
import { yup } from "react-router-typesafe-routes/yup";
import { string, number, date, object } from "yup";
// Basic types - type hint is auto-detected
yup(string())
yup(number())
yup(date())
// With validation
yup(string().email())
yup(number().positive())
// With custom parser
yup(string(), parser("string"))
```
--------------------------------
### Chaining Type Modifiers
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/quick-reference.md
Combine type modifiers for more complex type definitions. For example, create an array of strings with a default value or a required array of numbers.
```typescript
string().default("x").array() // Array with default
```
```typescript
number().defined().array() // Required array
```
--------------------------------
### Custom Validation Wrapper
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/validation-libraries.md
Use the base `type()` helper to wrap validation logic from external libraries. This example shows a hypothetical validation library integration.
```typescript
import { type, parser, Type, Validator } from "react-router-typesafe-routes";
// Example: hypothetical validation library
import { v, Schema } from "some-validation-library";
function custom(schema: Schema): Type {
return type(
(value: unknown) => schema.validate(value),
// Optionally provide a custom parser
parser("unknown")
);
}
const route = route({
params: {
id: custom(v.string().uuid())
}
});
```
--------------------------------
### Import Yup Support
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/README.md
Import Yup integration functions and the configure function from the Yup-specific entry point.
```typescript
import { yup, configure } from "react-router-typesafe-routes/yup";
```
--------------------------------
### Zod Validation Integration
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/quick-reference.md
Integrate Zod schemas for automatic type inference and validation of route parameters, search parameters, and state. Ensure Zod is installed and imported.
```typescript
import { zod } from "react-router-typesafe-routes/zod";
import { z } from "zod";
// Basic types - type hint is auto-detected
zod(z.string())
zod(z.number())
zod(z.boolean())
zod(z.date())
// Complex schemas
zod(z.string().email())
zod(z.number().int().positive())
zod(z.object({ ... }))
// With custom parser
zod(z.string(), parser("string"))
```
--------------------------------
### Route with state
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/api-route.md
Demonstrates defining a route with typed state and building the state object.
```APIDOC
## Route with state
### Description
Illustrates how to define a route that accepts typed state and how to construct the corresponding state object.
### Method
N/A (Code examples for library usage)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```typescript
import { route, boolean } from "react-router-typesafe-routes";
const detailRoute = route({
path: "detail/:id",
state: { fromList: boolean() }
});
const state = detailRoute.$buildState({
state: { fromList: true }
});
// Returns: { fromList: true }
```
### Response
N/A
```
--------------------------------
### Link with Route Parameters and State
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/quick-reference.md
Build navigation links using `$buildPath` for parameters and search parameters, and `$buildState` for route-specific state.
```typescript
Click
```
--------------------------------
### Define Custom Type with `type()`
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/api-type-helpers.md
Creates a custom route parameter type using the `type()` helper with a custom validator. This example defines a validator for positive integers.
```typescript
import { type } from "react-router-typesafe-routes";
// Custom validator
const positiveNumber = (value: unknown) => {
const num = Number(value);
if (!Number.isInteger(num) || num <= 0) {
throw new Error("Must be a positive integer");
}
return num;
};
const route = route({
path: "item/:id",
params: {
id: type(positiveNumber)
}
});
```
--------------------------------
### Implementing Custom Validators
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/README.md
Custom validator functions can be defined to enforce specific constraints. This example creates a 'positive' validator that throws an error if the input number is not positive.
```typescript
const positive = (value: number) => {
if (value <= 0) throw new Error("Must be positive");
return value;
};
const route = route({
params: { id: number(positive).defined() }
});
```
--------------------------------
### Import Zod Support
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/README.md
Import Zod integration functions and the configure function from the Zod-specific entry point.
```typescript
import { zod, configure } from "react-router-typesafe-routes/zod";
```
--------------------------------
### Import Standard Schema Support
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/README.md
Import standard schema integration functions, configure, and parser from the standard-schema entry point.
```typescript
import { schema, configure, parser } from "react-router-typesafe-routes/standard-schema";
```
--------------------------------
### Inline Child Routes
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/README.md
Define child routes directly within the parent route definition for simpler structures. Use $path() to get the absolute path pattern.
```typescript
import { route } from "react-router-typesafe-routes";
const user = route({ path: "user/:id", children: { details: route({ path: "details" }) } });
console.log(user.$path()); // "/user/:id"
console.log(user.details.$path()); // "/user/:id/details"
```
--------------------------------
### Providing Default Values for Search Params
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/README.md
The `.default()` method allows you to specify a fallback value for search parameters when they are absent or invalid. This example sets the default page to 1.
```typescript
const route = route({
searchParams: { page: number().default(1) }
});
// ?page=invalid → { page: 1 }
```
--------------------------------
### Configuring Custom Parser Factory
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/quick-reference.md
Shows how to configure the router with a custom parser factory, allowing for specialized parsing logic.
```typescript
import { configure, parser } from "react-router-typesafe-routes";
const { string, number } = configure({
parserFactory: parser
});
```
--------------------------------
### Default Validation Error Handling
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/README.md
By default, validation errors for route parameters are caught and converted to undefined. This snippet shows an example where an invalid number for 'id' results in 'id: undefined'.
```typescript
const route = route({
params: { id: number() }
});
// ?id=notanumber → { id: undefined }
```
--------------------------------
### Third-Party Validation Library Support: schema() (Standard Schema)
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/api-type-helpers.md
Demonstrates how to integrate with a standard schema parser (using Arktype) to define route parameters.
```APIDOC
### schema() (Standard Schema)
```typescript
import { schema, parser } from "react-router-typesafe-routes/standard-schema";
import { type } from "arktype";
const route = route({
params: {
id: schema(type("string.uuid"), parser("string"))
}
});
```
```
--------------------------------
### Programmatic Navigation with useNavigate
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/patterns-and-examples.md
Use the `useNavigate` hook to programmatically navigate to a route, optionally passing state and building the path with parameters and search parameters.
```typescript
import { useNavigate } from "react-router";
function Component() {
const navigate = useNavigate();
const handleClick = () => {
navigate(
myRoute.$buildPath({
params: { id: 123 },
searchParams: { tab: "comments" }
}),
{ state: myRoute.$buildState({ state: { edited: true } }) }
);
};
}
```
--------------------------------
### Define React Router Routes (Relative Paths)
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/README.md
Integrate typesafe route definitions using relative paths within React Router. The '$' symbol denotes the start of a path pattern for relative routing.
```tsx
import { Route, Routes } from "react-router";
import { root } from "./path/to/routes";
// Relative paths
{/* user/:userId */}
}>
{/* post/:postId? */}
{/* $ effectively defines path pattern start. */}
} />
;
```
--------------------------------
### Define Route with Search Param Arrays
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/patterns-and-examples.md
Demonstrates how to define search parameters that accept arrays of values and how to build URLs and access them in components.
```typescript
const filterRoute = route({
path: "products",
searchParams: {
// Array of IDs: ?category=1&category=2&category=3
categories: number().array(),
// Array of tags: ?tag=react&tag=typescript
tags: string().array()
}
});
// Build with arrays
const url = filterRoute.$buildPath({
searchParams: {
categories: [1, 2, 3],
tags: ["react", "typescript"]
}
});
// → "/products?categories=1&categories=2&categories=3&tags=react&tags=typescript"
// In component
function ProductList() {
const [params, setParams] = useTypedSearchParams(filterRoute);
// params.categories: number[] (empty array if absent)
// params.tags: string[] (empty array if absent)
}
```
--------------------------------
### Integrating Library Routes with React Router (Absolute Paths)
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/README.md
Use the $path() method to get absolute path patterns for React Router's components. Ensure parent components render an .
```typescript
import { Route, Routes } from "react-router-dom";
{/* '/user/:id' */}
}>
{/* '/user/:id/details' */}
} />
;
```
--------------------------------
### Configure Global Parser Factory with configure()
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/api-type-helpers.md
Globally set a custom parser factory for all type helpers by using the `configure()` function. This function takes an options object with a `parserFactory` that returns a parser. The returned object contains all type helpers, now using the custom factory.
```typescript
import { configure, parser } from "react-router-typesafe-routes";
// Custom parser factory
const customParserFactory = (hint) => {
return parser(hint);
};
const { type, string, number, boolean } = configure({
parserFactory: customParserFactory
});
// Now all these helpers use the custom parser
const myRoute = route({
params: { id: number() }
});
```
--------------------------------
### Get Typed Route Parameters
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/README.md
Retrieve typed parameters, search parameters, hash, and state from the current route using dedicated hooks. These hooks deserialize the route information based on the defined route structure.
```tsx
import {
useTypedParams,
useTypedSearchParams,
useTypedHash,
useTypedState,
} from "react-router-typesafe-routes";
import { root } from "./path/to/routes";
// { userId?: number; postId?: string; }
// Uses root.user.post.$deserializeParams internally.
const { userId, postId } = useTypedParams(root.user.post);
// { utm_campaign: string }.
// Uses root.user.post.$deserializeSearchParams internally.
const [{ utm_campaign }, setTypedSearchParams] = useTypedSearchParams(root.user.post);
// "info" | "comments" | undefined.
// Uses root.user.post.$deserializeHash internally.
const hash = useTypedHash(root.user.post);
// { fromUserList?: boolean }.
// Uses root.user.post.$deserializeState internally.
const { fromUserList } = useTypedState(root.user.post);
```
--------------------------------
### Core API Reference
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/DOCUMENTATION_SUMMARY.txt
Documentation for the main routing engine and type helper functions.
```APIDOC
## Core API Reference
This section details the primary functions and types exported by the library for defining and managing routes with type safety.
### Modules
- **`src/lib/route/route.ts`**: Contains the main routing engine.
- **`src/lib/types/types.ts`**: Implements the type system.
- **`src/lib/types/parser.ts`**: Defines the parser interface.
- **`src/lib/hooks/`**: Exports all React hooks for route interaction.
- **`src/zod/zod.ts`**: Zod integration utilities.
- **`src/yup/yup.ts`**: Yup integration utilities.
- **`src/standard-schema/standard-schema.ts`**: Standard Schema integration utilities.
### Key Concepts
- **Route Definition**: How to define routes with static type checking for parameters and search.
- **Type Helpers**: Utilities for creating and validating route types.
- **Hook Usage**: Examples of using hooks like `useNavigate`, `useParams`, `useSearch` within components.
- **React Router Integration**: How to integrate typesafe routes with React Router.
- **Advanced Patterns**: Demonstrations of complex routing scenarios like nested routes and state navigation.
```
--------------------------------
### Combined Hook Usage Example
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/api-hooks.md
This snippet illustrates how to import and utilize various type-safe hooks to access and manipulate route information within a React component. It defines a route with parameters, search parameters, hash options, and state, then uses the corresponding hooks to retrieve these values and conditionally render UI elements.
```typescript
import { route, number, string, boolean } from "react-router-typesafe-routes";
import {
useTypedParams,
useTypedSearchParams,
useTypedHash,
useTypedState
} from "react-router-typesafe-routes";
const postRoute = route({
path: "post/:postId",
params: { postId: number() },
searchParams: {
highlightCommentId: number()
},
hash: ["top", "comments", "related"],
state: { fromSearch: boolean() }
});
function PostPage() {
const { postId } = useTypedParams(postRoute);
const [search, setSearch] = useTypedSearchParams(postRoute);
const hash = useTypedHash(postRoute);
const { fromSearch } = useTypedState(postRoute);
return (
);
}
```
--------------------------------
### Third-Party Validation Library Support: yup()
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/api-type-helpers.md
Demonstrates how to integrate with the Yup validation library to define route parameters.
```APIDOC
### yup()
```typescript
import { yup } from "react-router-typesafe-routes/yup";
import { string as yupString } from "yup";
const route = route({
params: {
email: yup(yupString().email())
}
});
```
```
--------------------------------
### Import Main Entry Point Types
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/README.md
Import all necessary types and functions from the main entry point of the react-router-typesafe-routes library.
```typescript
import {
route,
type,
string,
number,
boolean,
date,
union,
parser,
configure,
useTypedParams,
useTypedSearchParams,
useTypedHash,
useTypedState
} from "react-router-typesafe-routes";
```
--------------------------------
### Creating Custom Parsers
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/configuration.md
You can implement the `Parser` interface to create custom serialization and deserialization logic for your routes.
```APIDOC
## Creating Custom Parsers
### Description
Implement the `Parser` interface to define custom serialization and deserialization logic.
### Interface
```typescript
interface Parser {
stringify(value: T, context: ParserContext): string;
parse(value: string, context: ParserContext): unknown;
}
```
### Example: Custom Entity Parser
This example demonstrates creating a custom parser for an entity type.
```typescript
import { Parser, ParserContext, ParserHint, parser } from "react-router-typesafe-routes";
type CustomParserHint = ParserHint | "entity";
type CustomParserType =
T extends "entity" ? { id: number } : ParserType>;
function customParser(
defaultHint?: T
): Parser, CustomParserHint> {
return {
stringify(value, { hint, kind }) {
const resolvedHint = hint ?? defaultHint;
if (resolvedHint === "entity") {
// Custom serialization for entities
return JSON.stringify((value as any).id);
}
// Fall back to built-in parser
const builtIn = parser();
return builtIn.stringify(value, { hint: resolvedHint as ParserHint, kind });
},
parse(value, { hint, kind }) {
const resolvedHint = hint ?? defaultHint;
if (resolvedHint === "entity") {
// Custom deserialization for entities
const id = JSON.parse(value);
return { id };
}
// Fall back to built-in parser
const builtIn = parser();
return builtIn.parse(value, { hint: resolvedHint as ParserHint, kind });
}
};
}
// Use custom parser
const myRoute = route({
params: { entity: type(entityValidator, customParser("entity")) }
});
```
```
--------------------------------
### Define Basic Route with Parameters and Search
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/README.md
Define a route with path parameters, optional path parameters, search parameters, hash fragments, navigation state, and child routes. Pathname pattern does not include leading/trailing slashes.
```typescript
import { route, number, string, boolean, union } from "react-router-typesafe-routes";
const userRoute = route({
// Pathname pattern (no leading/trailing slashes)
path: "user/:userId/post/:postId?",
// Override pathname param types
params: { userId: number() },
// Search/query parameters
searchParams: {
page: number(),
filter: string()
},
// URL hash fragment
hash: union(["info", "comments"]),
// Navigation state
state: { fromList: boolean() },
// Child routes
children: {
comments: route({ path: "comments" })
}
});
```
--------------------------------
### Route API Methods and Properties
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/api-route.md
Provides a comprehensive list of methods and properties for interacting with Route objects, including path building, parameter handling, and accessing route specifications.
```APIDOC
## Route API Methods and Properties
This section details the methods and properties available on a `Route` object, which is returned by route definitions.
### Methods
- **`$path(opts?)`**
- **Description**: Returns the path pattern of the route. Can be used to get absolute or relative paths.
- **Parameters**:
- `opts` (object) - Optional. Configuration options.
- `relative` (boolean) - Optional. If `true`, returns a relative path (without a leading slash or intermediate stars). Defaults to `false`.
- **Returns**: `string` - The path pattern.
- **`$buildPath(opts)`**
- **Description**: Builds a complete URL string including the pathname, search parameters, and hash.
- **Parameters**:
- `opts` (object) - Required. Options for building the path.
- `pathname` (object) - Pathname parameters.
- `searchParams` (object) - Search parameters.
- `hash` (string) - Hash value.
- `state` (object | unknown) - Navigation state.
- **Returns**: `string` - A fully constructed URL string (e.g., `/user/1?page=2#info`).
- **`$buildPathname(opts)`**
- **Description**: Builds only the pathname part of the URL, optionally as a relative path.
- **Parameters**:
- `opts` (object) - Required. Options for building the pathname.
- `relative` (boolean) - Optional. If `true`, returns a relative pathname (e.g., `user/1`). Defaults to `false`.
- **Returns**: `string` - The pathname string.
- **`$buildSearch(opts)`**
- **Description**: Builds only the query string part of the URL.
- **Parameters**:
- `opts` (object) - Required. Options for building the search string.
- `searchParams` (object) - Search parameters.
- **Returns**: `string` - The query string (e.g., `?page=2&filter=active`) or an empty string if no search parameters are provided.
- **`$buildHash(opts)`**
- **Description**: Builds only the hash part of the URL.
- **Parameters**:
- `opts` (object) - Required. Options for building the hash.
- `hash` (string) - The hash value.
- **Returns**: `string` - The hash string (e.g., `#info`).
- **`$buildState(opts)`**
- **Description**: Builds the serialized state for navigation.
- **Parameters**:
- `opts` (object) - Required. Options for building the state.
- `state` (object | unknown) - The state to serialize.
- **Returns**: `object | unknown` - The serialized state.
- **`$serializeParams(opts)`**
- **Description**: Serializes pathname parameters into string format. Primarily used internally by build methods.
- **Parameters**:
- `opts` (object) - Required. Options containing pathname parameters.
- **Returns**: `Record` - An object with serialized pathname parameters.
- **`$serializeSearchParams(opts)`**
- **Description**: Serializes search parameters into a `URLSearchParams` object. Supports mixing untyped parameters.
- **Parameters**:
- `opts` (object) - Required. Options containing search parameters.
- **Returns**: `URLSearchParams` - A `URLSearchParams` object.
- **`$deserializeParams(params)`**
- **Description**: Deserializes and validates pathname parameters from React Router's `useParams()` result.
- **Parameters**:
- `params` (Record) - The parameters object from `useParams()`.
- **Returns**: `object` - The deserialized and validated parameters.
- **`$deserializeSearchParams(searchParams)`**
- **Description**: Deserializes and validates search parameters from React Router's `useSearchParams()` result.
- **Parameters**:
- `searchParams` (URLSearchParams) - The `URLSearchParams` object from `useSearchParams()`.
- **Returns**: `object` - The deserialized and validated search parameters.
- **`$deserializeHash(hash)`**
- **Description**: Deserializes and validates the hash from `location.hash`.
- **Parameters**:
- `hash` (string) - The hash string from `location.hash`.
- **Returns**: `value` - The deserialized hash value.
- **`$deserializeState(state)`**
- **Description**: Deserializes and validates navigation state from `location.state`.
- **Parameters**:
- `state` (unknown) - The state value from `location.state`.
- **Returns**: `object | unknown` - The deserialized and validated state.
### Properties
- **`$spec`**
- **Type**: `RouteSpec`
- **Description**: Contains the resolved type objects and path configuration for the route.
- **`$`**
- **Type**: `RouteChildren`
- **Description**: Child routes, stripped of the parent path pattern. Used for relative route definitions.
- **`[childName]`**
- **Type**: `Route`
- **Description**: Direct access to child routes by their defined name.
```
--------------------------------
### Third-Party Validation Library Support: zod()
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/api-type-helpers.md
Demonstrates how to integrate with the Zod validation library to define route parameters.
```APIDOC
## Third-Party Validation Library Support
Additional entry points provide type helpers for popular validation libraries:
### zod()
```typescript
import { zod } from "react-router-typesafe-routes/zod";
import { z } from "zod";
const route = route({
params: {
id: zod(z.string().uuid())
}
});
```
```
--------------------------------
### Import Zod Parser
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/quick-reference.md
Import the Zod integration for defining route schemas.
```typescript
// Zod
import { zod } from "react-router-typesafe-routes/zod";
```
--------------------------------
### Define Nested Routes
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/patterns-and-examples.md
Demonstrates how to define nested routes with their own paths and how to access them.
```typescript
const postRoute = route({
path: "post/:postId?",
params: { postId: string() },
children: {
comments: route({ path: "comments" }),
settings: route({ path: "settings" })
}
});
// Access nested routes
postRoute.comments.$path(); // "/post/:postId?/comments"
postRoute.settings.$path(); // "/post/:postId?/settings"
```
--------------------------------
### React Hooks Reference
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/DOCUMENTATION_SUMMARY.txt
Documentation for the React hooks provided by the library for interacting with routes.
```APIDOC
## React Hooks Reference
This section documents the custom React hooks provided by the library to enhance type safety when working with routes in your components.
### `useParams()`
**Description**: Retrieves typed route parameters.
**Usage**: Use this hook within a component rendered by a route that has defined parameters.
**Type Parameters**:
- `TParams`: The expected type of the route parameters.
**Return Value**: An object containing the route parameters, typed according to `TParams`.
### `useSearch()`
**Description**: Retrieves typed search (query) parameters from the URL.
**Usage**: Use this hook to access and utilize search parameters in your components.
**Type Parameters**:
- `TSearch`: The expected type of the search parameters.
**Return Value**: An object containing the search parameters, typed according to `TSearch`.
### `useNavigate()`
**Description**: Provides a type-safe way to navigate between routes.
**Usage**: Call this hook to get a navigation function that accepts route paths and parameters.
**Return Value**: A navigation function that ensures type safety for navigation targets and parameters.
```
--------------------------------
### Use Typed Hash Hook
Source: https://github.com/fenok/react-router-typesafe-routes/blob/dev/_autodocs/api-hooks.md
Demonstrates how to use the useTypedHash hook to access and conditionally render components based on the URL hash. Requires importing the hook and defining a route with a hash specification.
```typescript
import { route, union } from "react-router-typesafe-routes";
import { useTypedHash } from "react-router-typesafe-routes";
import { useNavigate } from "react-router";
const detailRoute = route({
path: "detail/:id",
hash: union(["info", "comments", "stats"])
});
function Detail() {
const hash = useTypedHash(detailRoute);
const navigate = useNavigate();
return (