### Quick Start Routing Setup Source: https://github.com/strblr/typeroute/blob/master/README.md A minimal, complete routing setup with a layout, home, and about pages. This example demonstrates basic route definition, component assignment, and router configuration. ```tsx import { route, RouterRoot, Outlet, Link } from "@typeroute/router"; // Layout route const app = route("/").component(AppLayout); function AppLayout() { return (
); } // Page routes const home = app.component(() =>

Welcome home

); const about = app.route("/about").component(() =>

About us

); // Router setup const routes = [home, about]; export function App() { return ; } declare module "@typeroute/router" { interface Register { routes: typeof routes; } } ``` -------------------------------- ### Route Ranking Example Source: https://github.com/strblr/typeroute/blob/master/README.md Illustrates the weight calculation for different route patterns matching the '/users/new' path. ```plaintext /users/new → [static, static] → weights [2, 2] ✓ Wins /users/:id → [static, dynamic] → weights [2, 1] /users/* → [static, wildcard] → weights [2, 0] ``` -------------------------------- ### Basic RouterRoot Setup Source: https://github.com/strblr/typeroute/blob/master/README.md Use the RouterRoot component with your collected routes for the simplest setup. This creates an internal router instance. ```tsx import { RouterRoot } from "@typeroute/router"; const routes = [home, about]; function App() { return ; } ``` -------------------------------- ### TypeRoute App Example Source: https://github.com/strblr/typeroute/blob/master/README.md This example demonstrates an equivalent application structure using the TypeRoute library, showcasing its route definition and component outlet system. ```tsx import { route, RouterRoot, Outlet, Link } from "@typeroute/router"; const home = route("/").component(Layout).index(Home); const about = home.route("/about").component(About); const notFound = home.route("/*").component(NotFound); const routes = [home, about, notFound]; function Layout() { return (
); } function App() { return ; } declare module "@typeroute/router" { interface Register { routes: typeof routes; } } ``` -------------------------------- ### Install TypeRoute Devtools Source: https://github.com/strblr/typeroute/blob/master/README.md Install the devtools package using npm. This package provides tools for inspecting routes and navigation state. ```bash npm install @typeroute/devtools ``` -------------------------------- ### Wouter App Example Source: https://github.com/strblr/typeroute/blob/master/README.md This is a typical application structure using the Wouter routing library, demonstrating navigation and route handling. ```tsx import { Router, Route, Switch, Link } from "wouter"; function App() { return (
); } ``` -------------------------------- ### Defining User Routes Source: https://github.com/strblr/typeroute/blob/master/README.md Example routes for user-related paths, including static, dynamic, and wildcard segments. ```tsx const userNew = route("/users/new").component(NewUser); const userProfile = route("/users/:id").component(UserProfile); const userCatchAll = route("/users/*").component(UserCatchAll); ``` -------------------------------- ### Install TypeRoute Router Source: https://github.com/strblr/typeroute/blob/master/README.md Install the TypeRoute router package using npm. TypeRoute requires React 18 or higher. ```bash npm install @typeroute/router ``` -------------------------------- ### Instantiate Router with Options Source: https://github.com/strblr/typeroute/blob/master/README.md Create a new Router instance with various configuration options. Examples include providing routes, setting a basePath, using a custom history instance, or providing a context. ```tsx const router = new Router({ routes }); const router = new Router({ routes, basePath: "/app" }); const router = new Router({ routes, history: new HashHistory() }); const router = new Router({ routes, context: { queryClient } }); ``` -------------------------------- ### Preload User Data Before Navigation Source: https://github.com/strblr/typeroute/blob/master/README.md Use .preload() to fetch user data based on route parameters and search values before navigating to a user profile. This example uses TanStack Query's prefetchQuery for data fetching. ```tsx const userProfile = route("/users/:id") .search(z.object({ tab: z.enum(["posts", "comments"])).catch("posts")) .preload(async ({ params, search, context }) => { await queryClient.prefetchQuery({ queryKey: ["user", params.id, search.tab], queryFn: () => fetchUser(params.id, search.tab) }); }) .component(UserProfile); ``` -------------------------------- ### Root Error Boundary Setup Source: https://github.com/strblr/typeroute/blob/master/README.md Place an error boundary at the root of your application to catch any unhandled errors. The error boundary automatically resets when navigation occurs, ensuring a fresh start for new routes. ```tsx const app = route("/").error(ErrorPage).component(AppLayout); ``` -------------------------------- ### History Middleware for Logging Source: https://github.com/strblr/typeroute/blob/master/README.md Extend history behavior for logging or analytics by monkey-patching the history instance. This example adds console logging to `go` and `push` methods. ```tsx function withLogging(history: HistoryLike): HistoryLike { const { go, push } = history; history.go = delta => { console.log("Navigate", delta > 0 ? "forward" : "back"); go(delta); }; history.push = options => { console.log("Navigate to", options.url); push(options); }; return history; } ``` -------------------------------- ### Compose History Middlewares Source: https://github.com/strblr/typeroute/blob/master/README.md Compose multiple history middleware functions to chain their functionalities. This example composes logging and analytics middleware. ```tsx // Compose middlewares const router = new Router({ routes, history: withLogging(withAnalytics(new BrowserHistory())) }); ``` -------------------------------- ### Client-Side Hydration with BrowserHistory Source: https://github.com/strblr/typeroute/blob/master/README.md On the client, use the default BrowserHistory for hydration. This snippet shows the basic setup for client-side rendering. ```tsx // client.tsx import { hydrateRoot } from "react-dom/client"; import { RouterRoot } from "@typeroute/router"; import { routes } from "./routes"; hydrateRoot(rootElement, ); ``` -------------------------------- ### Layout Component with DocumentTitle Source: https://github.com/strblr/typeroute/blob/master/README.md Example of placing the DocumentTitle component within a layout. This ensures the title updates correctly as users navigate through the application. ```tsx function Layout() { return ( <>
); } ``` -------------------------------- ### Get a Route by Pattern Source: https://github.com/strblr/typeroute/blob/master/README.md Retrieve a route object using its pattern string. Throws an error if the route is not found. ```tsx const route = router.getRoute("/users/:id"); ``` -------------------------------- ### View Transitions CSS Animation Source: https://github.com/strblr/typeroute/blob/master/README.md Add CSS rules to control the animation duration of view transitions. This example sets a 200ms duration for old and new views. ```css ::view-transition-old(root), ::view-transition-new(root) { animation-duration: 200ms; } ``` -------------------------------- ### History Middleware for Analytics Source: https://github.com/strblr/typeroute/blob/master/README.md Extend history behavior for logging or analytics by monkey-patching the history instance. This example adds analytics tracking to the `push` method. ```tsx function withAnalytics(history: HistoryLike): HistoryLike { const { push } = history; history.push = options => { analytics.track("page_view", { url: options.url }); push(options); }; return history; } ``` -------------------------------- ### Get Current Location with history.location() Source: https://github.com/strblr/typeroute/blob/master/README.md Retrieve the current location details, including path, parsed search parameters, and history state. ```tsx const { path, search, state } = history.location(); // path: "/users/42" // search: { tab: "posts", page: 2 } // state: any state passed during navigation ``` -------------------------------- ### Define Dynamic Page Titles with Route Handles Source: https://github.com/strblr/typeroute/blob/master/README.md Attach a 'title' handle to routes to dynamically update the browser's document title. This example shows how to define titles for layout, home, and settings routes. ```tsx const layout = route("/").handle({ title: "App" }).component(Layout); const home = layout.handle({ title: "Home" }).component(HomePage); const settings = layout .route("/settings") .handle({ title: "Settings" }) .component(SettingsPage); ``` -------------------------------- ### Register Routes in Root App Component Source: https://github.com/strblr/typeroute/blob/master/README.md Imports all routes, registers them using module augmentation, and renders the RouterRoot component. This setup automatically picks up route definitions from the aggregated routes namespace. ```tsx // app.tsx import { RouterRoot } from "@typeroute/router"; import * as routes from "./pages/routes"; export function App() { return ; } declare module "@typeroute/router" { interface Register { routes: typeof routes; } } ``` -------------------------------- ### Configure Data Fetching with StaleTime Source: https://github.com/strblr/typeroute/blob/master/README.md Configure TanStack Query's prefetchQuery with staleTime to prevent refetches within a specified duration, ensuring data freshness. This example sets a staleTime of 60 seconds. ```tsx await queryClient.prefetchQuery({ queryKey: ["user", params.id], queryFn: () => fetchUser(params.id), staleTime: 60_000 // No refetch within 60s }); ``` -------------------------------- ### Router Constructor Source: https://github.com/strblr/typeroute/blob/master/README.md Initializes a new Router instance with provided options, which can include routes, a base path, a custom history instance, or a router context. ```APIDOC ## `new Router(options)` Creates a new router. - `options` - `RouterOptions` - Router configuration - Returns: `Router` - A new router instance ```tsx const router = new Router({ routes }); const router = new Router({ routes, basePath: "/app" }); const router = new Router({ routes, history: new HashHistory() }); const router = new Router({ routes, context: { queryClient } }); ``` ``` -------------------------------- ### Link with 'render' preload strategy Source: https://github.com/strblr/typeroute/blob/master/README.md Use 'render' to preload as soon as the link mounts. This is suitable for routes that are highly likely to be visited. ```tsx Next step ``` -------------------------------- ### Passing Router Context for Shared Instances Source: https://github.com/strblr/typeroute/blob/master/README.md Illustrates how to pass arbitrary data, such as a query client instance, as context to the router. This context can then be accessed within preload functions. ```tsx ; declare module "@typeroute/router" { interface Register { routes: typeof routes; context: { queryClient: QueryClient }; } } ``` -------------------------------- ### useNavigate() Source: https://github.com/strblr/typeroute/blob/master/README.md Returns a navigation function for programmatic navigation. ```APIDOC ## useNavigate() ### Description Returns a navigation function for programmatic navigation. ### Returns `(options: NavigateOptions | HistoryPushOptions | number) => void` - The navigate function. ### Example ```tsx const navigate = useNavigate(); navigate({ to: "/home" }); navigate(-1); ``` ``` -------------------------------- ### useRouter() Source: https://github.com/strblr/typeroute/blob/master/README.md Returns the Router instance from the context. ```APIDOC ## useRouter() ### Description Returns the Router instance from the context. ### Returns `Router` - The router instance. ### Example ```tsx const router = useRouter(); ``` ``` -------------------------------- ### Link with 'intent' preload strategy Source: https://github.com/strblr/typeroute/blob/master/README.md Use 'intent' to preload when the user hovers or focuses the link. This is the most common strategy, balancing eager loading with bandwidth efficiency. ```tsx Heavy page ``` -------------------------------- ### Get Router Instance Source: https://github.com/strblr/typeroute/blob/master/README.md Retrieves the current Router instance from the component's context. This hook is essential for accessing router-level functionalities. ```tsx const router = useRouter(); ``` -------------------------------- ### RouterRoot Component Source: https://github.com/strblr/typeroute/blob/master/README.md Sets up the routing context and renders your routes. It accepts either router options or a router instance. ```APIDOC ## RouterRoot Component ### Description Sets up routing context and renders your routes. ### Props - `props` - `RouterOptions | { router: Router }` - Either router options (same as the `Router` constructor) or a router instance. ### Usage Examples ```tsx ``` ``` -------------------------------- ### useOutlet() Source: https://github.com/strblr/typeroute/blob/master/README.md Returns the next rendered content in the current component stack. ```APIDOC ## useOutlet() ### Description Returns the next rendered content in the current component stack. ### Returns `ReactNode` - The next rendered outlet content or null. ### Example ```tsx const outlet = useOutlet(); ``` ``` -------------------------------- ### Get Outlet Content Source: https://github.com/strblr/typeroute/blob/master/README.md Returns the content that should be rendered in the current outlet. This is typically used within layout components to render nested routes. ```tsx const outlet = useOutlet(); ``` -------------------------------- ### Define Index Route with .component() Source: https://github.com/strblr/typeroute/blob/master/README.md Use .component() chained directly on a layout route to create an index route. The overview route matches the layout's path and renders the layout with the overview component. ```tsx const dashboard = route("/dashboard").component(DashboardLayout); const overview = dashboard.component(Overview); const settings = dashboard.route("/settings").component(Settings); ``` -------------------------------- ### Get Current Match Handles Source: https://github.com/strblr/typeroute/blob/master/README.md Retrieves an array of handles associated with the current route match. Handles are typically used for data loading or other side effects. ```tsx const handles = useHandles(); ``` -------------------------------- ### route(pattern) Source: https://github.com/strblr/typeroute/blob/master/README.md Creates a new route with a specified path pattern. This is the entry point for defining a new route. ```APIDOC ## route(pattern) ### Description Creates a new route with a specified path pattern. This is the entry point for defining a new route. ### Parameters #### Path Parameters - **pattern** (string) - Required - The route path pattern (e.g., `"/users"`, `"/users/:id"`, `"/*"`) ### Returns - **Route** - A new route object ``` -------------------------------- ### Get Typed Route Parameters Source: https://github.com/strblr/typeroute/blob/master/README.md Extracts and types path parameters for a given route pattern or object. Ensure the `userRoute` variable is defined elsewhere with the correct route pattern. ```tsx const { id } = useParams(userRoute); ``` -------------------------------- ### Define Basic Routes Source: https://github.com/strblr/typeroute/blob/master/README.md Create basic routes using the `route()` function and chain the `.component()` method to associate a React component with each route. Route building is immutable. ```tsx import { route } from "@typeroute/router"; const home = route("/").component(HomePage); const about = route("/about").component(AboutPage); ``` -------------------------------- ### Create Basic Routes Source: https://github.com/strblr/typeroute/blob/master/README.md Use the `route()` function to create new route objects with specified path patterns. Supports exact paths, dynamic segments, and catch-all patterns. ```tsx const users = route("/users"); const user = route("/users/:id"); const catchAll = route("/*"); ``` -------------------------------- ### Get Current Location Source: https://github.com/strblr/typeroute/blob/master/README.md Retrieves the current location object, which includes the path, parsed search parameters, and history state. Useful for displaying dynamic content based on the URL. ```tsx const { path, search, state } = useLocation(); ``` -------------------------------- ### router.preload Source: https://github.com/strblr/typeroute/blob/master/README.md Initiates the preloading process for a specified route, which can be useful for code-splitting and performance optimization. ```APIDOC ## `router.preload(options)` Triggers preloading for a route. - `options` - `NavigateOptions` - Type-safe navigation options - Returns: `Promise` - Resolves when preloaded ```tsx await router.preload({ to: "/user/:id", params: { id: "42" } }); await router.preload({ to: searchPage, search: { q: "test" } }); ``` ``` -------------------------------- ### Get and Set Search Parameters Source: https://github.com/strblr/typeroute/blob/master/README.md Provides validated search parameters for a route and a function to update them. The setter can perform partial updates, replace the entire search, or use an updater function. ```tsx const [search, setSearch] = useSearch(searchRoute); setSearch({ page: 2 }); setSearch(prev => ({ page: prev.page + 1 })); setSearch({ page: 1 }, true); // Replace instead of push ``` -------------------------------- ### middleware() Source: https://github.com/strblr/typeroute/blob/master/README.md Creates a new middleware object. Middlewares can be built using methods similar to Route, excluding `.route()`. ```APIDOC ## middleware() ### Description Creates a new middleware object. Middlewares support all the same builder methods as `Route` except `.route()`. ### Returns `Middleware` - A new middleware object. ### Example ```tsx const pagination = middleware().search( z.object({ page: z.coerce.number().catch(1), limit: z.coerce.number().catch(10) }) ); const auth = middleware() .handle({ requiresAuth: true }) .component(AuthRedirect); ``` ``` -------------------------------- ### Route.use(middleware) Source: https://github.com/strblr/typeroute/blob/master/README.md Applies a middleware to the current route, merging its configuration. Middleware can handle requests before they reach the component. ```APIDOC ## Route.use(middleware) ### Description Applies a middleware to the current route, merging its configuration. Middleware can handle requests before they reach the component. ### Parameters #### Path Parameters - **middleware** (Middleware) - Required - A middleware object ### Returns - **Route** - A new route object ``` -------------------------------- ### Create Pagination Middleware Source: https://github.com/strblr/typeroute/blob/master/README.md Creates a middleware for handling pagination parameters from the search query. It defaults to page 1 and limit 10 if not provided. ```tsx const pagination = middleware().search( z.object({ page: z.coerce.number().catch(1), limit: z.coerce.number().catch(10) }) ); ``` -------------------------------- ### router.matchAll Source: https://github.com/strblr/typeroute/blob/master/README.md Finds the best matching route for a given path from all registered routes in the router. ```APIDOC ## `router.matchAll(path)` Finds the best match from all registered routes. - `path` - `string` - The path to match against - Returns: `Match | null` - The best match or null if no route matches ```tsx const match = router.matchAll("/users/42"); // Returns the best match or null ``` ``` -------------------------------- ### Programmatic Navigation with Router Instance Source: https://github.com/strblr/typeroute/blob/master/README.md Access the router instance directly via useRouter() and call its navigate method for programmatic navigation. ```tsx router.navigate({ to: "/login" }); ``` -------------------------------- ### Loose vs. Strict Active Matching Source: https://github.com/strblr/typeroute/blob/master/README.md Links automatically detect active state. 'Loose matching' (default) considers a link active if the current path starts with the link's target. Use the `strict` prop for exact path matching. ```tsx Active on /dashboard and deeper paths Active only on /dashboard ``` -------------------------------- ### useMatch(options) Source: https://github.com/strblr/typeroute/blob/master/README.md Checks if a route matches the current path based on provided options. ```APIDOC ## useMatch(options) ### Description Checks if a route matches the current path based on provided options. ### Parameters #### Path Parameters - **options** (`MatchOptions`) - Matching options. ### Returns `Match | null` - The match result or null if no match. ### Example ```tsx const match = useMatch({ from: "/users/:id" }); const strictMatch = useMatch({ from: "/users", strict: true }); const filteredMatch = useMatch({ from: "/users/:id", params: { id: "admin" } }); ``` ``` -------------------------------- ### Link with Path Parameters Source: https://github.com/strblr/typeroute/blob/master/README.md When a route has non-optional path parameters, provide the `params` prop to specify their values. This ensures correct URL construction for dynamic routes. ```tsx View post ``` -------------------------------- ### Link with custom preload delay Source: https://github.com/strblr/typeroute/blob/master/README.md Customize the delay before preloading is triggered by setting the `preloadDelay` prop. This helps prevent unwanted preloads from rapid interactions. ```tsx Heavy page ``` -------------------------------- ### Define Routes with Suffix and Wildcard Segments Source: https://github.com/strblr/typeroute/blob/master/README.md Define routes with suffix matching for file extensions and wildcard segments that capture everything after a certain point. Supports optional wildcard segments. ```tsx const suffix = route("/movies/:title.(mp4|mov)"); const notFound = route("/*").component(NotFoundPage); const files = route("/files/*").component(FileBrowser); const optional = route("/books/*?").component(FileBrowser); ``` -------------------------------- ### Create Reusable Middlewares Source: https://github.com/strblr/typeroute/blob/master/README.md Create reusable route configurations using the `middleware()` function. Middlewares can define search params, handles, and components. ```typescript import { middleware } from "@typeroute/router"; const pagination = middleware().search( z.object({ page: z.coerce.number().catch(1), limit: z.coerce.number().catch(10) }) ); const auth = middleware() .handle({ requiresAuth: true }) .component(AuthRedirect); ``` -------------------------------- ### Navigate Component Source: https://github.com/strblr/typeroute/blob/master/README.md Redirects the user on render, used for declarative navigation. ```APIDOC ## Navigate Component ### Description Redirects on render. ### Props - `props` - `NavigateOptions` - The navigation target. ### Usage Example ```tsx ``` ``` -------------------------------- ### useHandles() Source: https://github.com/strblr/typeroute/blob/master/README.md Returns the handles associated with the current route match. ```APIDOC ## useHandles() ### Description Returns the handles associated with the current route match. ### Returns `Handle[]` - Array of handles. ### Example ```tsx const handles = useHandles(); ``` ``` -------------------------------- ### Define and Chain Route Handles Source: https://github.com/strblr/typeroute/blob/master/README.md Define static metadata for routes using the `.handle()` method. Handles can be chained to create a hierarchy of metadata. ```tsx const dashboard = route("/dashboard") .handle({ title: "Dashboard", requiresAuth: true }) .component(DashboardPage); const settings = dashboard .route("/settings") .handle({ title: "Settings" }) .component(SettingsPage); ``` -------------------------------- ### Apply Middleware to a Route Source: https://github.com/strblr/typeroute/blob/master/README.md Apply created middlewares to a route using the `.use()` method. Middleware configurations merge into the route's configuration. ```typescript const userPage = route("/users").use(pagination).component(UserPage); function UserPage() { const [search] = useSearch(userPage); // search.page: number // search.limit: number } ``` -------------------------------- ### Programmatic Navigation with useNavigate Source: https://github.com/strblr/typeroute/blob/master/README.md Use the useNavigate hook for navigation triggered by code, such as in event handlers. It accepts navigation options like 'to', 'params', 'search', 'replace', and 'state'. ```tsx import { useNavigate } from "@typeroute/router"; function LoginForm() { const navigate = useNavigate(); const onSubmit = async () => { await login(); navigate({ to: "/dashboard" }); }; // ... } ``` -------------------------------- ### Define Index Route with .index() Source: https://github.com/strblr/typeroute/blob/master/README.md Use .index() to combine layout and index content into a single navigable route. This renders the index component when no outlet content is present. ```tsx const dashboard = route("/dashboard") .component(DashboardLayout) .index(Overview); const settings = dashboard.route("/settings").component(Settings); ``` -------------------------------- ### Create Authentication Middleware Source: https://github.com/strblr/typeroute/blob/master/README.md Creates a middleware that requires authentication and integrates an `AuthRedirect` component. This is useful for protecting routes. ```tsx const auth = middleware() .handle({ requiresAuth: true }) .component(AuthRedirect); ``` -------------------------------- ### Configure Index Route Source: https://github.com/strblr/typeroute/blob/master/README.md The `.index()` method sets a fallback component to be rendered when no other outlet content is available for a given route. This is often used for default views within a layout. ```tsx const dashboard = route("/dashboard") .component(DashboardLayout) .index(Overview); ``` -------------------------------- ### Route Ranking for Dynamic Path Source: https://github.com/strblr/typeroute/blob/master/README.md Shows the ranking for routes matching the '/users/42' path, highlighting dynamic segment matching. ```plaintext /users/new → doesn't match /users/:id → [static, dynamic] → weights [2, 1] ✓ Wins /users/* → [static, wildcard] → weights [2, 0] ``` -------------------------------- ### HashHistory Implementation Source: https://github.com/strblr/typeroute/blob/master/README.md Employ HashHistory for static file hosting or environments where server-side routing configuration is not possible. It stores the path in the URL hash, resulting in URLs like "/#/posts/123". ```tsx import { HashHistory } from "@typeroute/router"; ; ``` -------------------------------- ### Create a URL String Source: https://github.com/strblr/typeroute/blob/master/README.md Build a URL string from type-safe navigation options. This method is useful for generating links or constructing URLs programmatically. ```tsx const url = router.createUrl({ to: userProfile, params: { id: "42" } }); // Returns "/users/42" ``` -------------------------------- ### Inheritance of Preload Functions in Nested Routes Source: https://github.com/strblr/typeroute/blob/master/README.md Demonstrates how preload functions defined on a parent route are inherited by its child routes. The '/dashboard/settings' route will execute the prefetchDashboardData function defined for '/dashboard'. ```tsx const dashboard = route("/dashboard") .preload(prefetchDashboardData) .component(DashboardLayout); const settings = dashboard.route("/settings").component(Settings); // Preloading /dashboard/settings runs prefetchDashboardData ``` -------------------------------- ### Route.preload(preload) Source: https://github.com/strblr/typeroute/blob/master/README.md Registers an asynchronous preload function for the route, which can fetch data before the route is rendered. ```APIDOC ## Route.preload(preload) ### Description Registers an asynchronous preload function for the route, which can fetch data before the route is rendered. ### Parameters #### Path Parameters - **preload** ( (options: PreloadOptions) => Promise ) - Required - An async function receiving typed `params`, `search`, and `context` ### Returns - **Route** - A new route object ``` -------------------------------- ### Route.suspense(fallback) Source: https://github.com/strblr/typeroute/blob/master/README.md Wraps subsequent route components in a Suspense boundary, providing a fallback UI while components are loading. ```APIDOC ## Route.suspense(fallback) ### Description Wraps subsequent route components in a Suspense boundary, providing a fallback UI while components are loading. ### Parameters #### Path Parameters - **fallback** (ComponentType) - Required - The fallback component to show while suspended ### Returns - **Route** - A new route object ``` -------------------------------- ### Navigate with Options Source: https://github.com/strblr/typeroute/blob/master/README.md The navigate function accepts various options for specifying the destination, parameters, search queries, and state. ```tsx navigate({ to: userProfile, params: { id: "42" }, search: { tab: "posts" } }); navigate({ to: "/login", replace: true }); navigate({ to: "/checkout", state: { from: "cart" } }); ``` -------------------------------- ### Configure Default Link Options Source: https://github.com/strblr/typeroute/blob/master/README.md Set global defaults for all Link components using `defaultLinkOptions` on the router. This is useful for consistent styling and preload behavior across your application. ```tsx ``` -------------------------------- ### router.createUrl Source: https://github.com/strblr/typeroute/blob/master/README.md Constructs a URL string based on type-safe navigation options, allowing for the creation of deep links or navigation targets. ```APIDOC ## `router.createUrl(options)` Builds a URL string. - `options` - `NavigateOptions` - Type-safe navigation options - Returns: `string` - The constructed URL ```tsx const url = router.createUrl({ to: userProfile, params: { id: "42" } }); // Returns "/users/42" ``` ``` -------------------------------- ### TypeRoute History Implementations Source: https://github.com/strblr/typeroute/blob/master/README.md Instantiate different history implementations based on your application's needs: BrowserHistory, HashHistory, or MemoryHistory. ```tsx new BrowserHistory(); // Browser History API (/posts/123). Default. new HashHistory(); // URL hash (/#/posts/123). new MemoryHistory("/initial"); // In-memory only. ``` -------------------------------- ### Apply Middleware to Route Source: https://github.com/strblr/typeroute/blob/master/README.md The `.use()` method applies middleware to a route, merging its configuration. This is useful for adding common functionality like authentication or logging to multiple routes. ```tsx const auth = middleware().component(AuthRedirect); const dashboard = route("/dashboard").use(auth).component(Dashboard); ``` -------------------------------- ### Outlet Component Source: https://github.com/strblr/typeroute/blob/master/README.md Renders the next content in the current component stack, typically used within layout components. ```APIDOC ## Outlet Component ### Description Renders the next content in the current component stack. ### Usage Example ```tsx function Layout() { return (
); } ``` ``` -------------------------------- ### Link with Search Parameters Source: https://github.com/strblr/typeroute/blob/master/README.md Pass search parameters using the `search` prop along with `params` if needed. This allows for filtering or additional context in the URL. ```tsx User posts ``` -------------------------------- ### Declarative Navigation with Navigate Component Source: https://github.com/strblr/typeroute/blob/master/README.md Use the Navigate component for redirects triggered by rendering. It navigates as soon as it mounts, suitable for state-driven redirects. ```tsx import { Navigate } from "@typeroute/router"; function ProtectedPage() { const { isAuthenticated } = useAuth(); if (!isAuthenticated) { return ; } return
Protected content
; } ``` -------------------------------- ### Route.handle(handle) Source: https://github.com/strblr/typeroute/blob/master/README.md Attaches arbitrary static metadata to the route, which can be used for route guards or other purposes. ```APIDOC ## Route.handle(handle) ### Description Attaches arbitrary static metadata to the route, which can be used for route guards or other purposes. ### Parameters #### Path Parameters - **handle** (Handle) - Required - Arbitrary metadata ### Returns - **Route** - A new route object ``` -------------------------------- ### useLocation() Source: https://github.com/strblr/typeroute/blob/master/README.md Returns the current location object, including path, parsed search parameters, and history state. ```APIDOC ## useLocation() ### Description Returns the current location object, including path, parsed search parameters, and history state. ### Returns `HistoryLocation` - The current location. ### Example ```tsx const { path, search, state } = useLocation(); ``` ``` -------------------------------- ### Server-Side Rendering with MemoryHistory Source: https://github.com/strblr/typeroute/blob/master/README.md Use MemoryHistory on the server, initialized with the request URL, for SSR. The ssrContext captures redirect information. ```tsx // server.tsx import { renderToString } from "react-dom/server"; import { RouterRoot, MemoryHistory, type SSRContext } from "@typeroute/router"; import { routes } from "./routes"; function handleRequest(req: Request) { const ssrContext: SSRContext = {}; const html = renderToString( ); if (ssrContext.redirect) { return Response.redirect(ssrContext.redirect); } // ... Send pre-rendered HTML } ``` -------------------------------- ### RouterRoot with Custom Router Instance Source: https://github.com/strblr/typeroute/blob/master/README.md Create a Router instance outside of React for access from non-React contexts, then pass it to RouterRoot. ```tsx import { Router, RouterRoot } from "@typeroute/router"; const router = new Router({ routes }); // Now you can navigate from anywhere router.navigate({ to: "/about" }); // And pass the instance to RouterRoot function App() { return ; } ``` -------------------------------- ### Attach Static Metadata Source: https://github.com/strblr/typeroute/blob/master/README.md Use the `.handle()` method to attach arbitrary static metadata to a route. This data can be accessed later for purposes like route guards or data fetching. ```tsx const admin = route("/admin").handle({ requiresAuth: true }); ``` -------------------------------- ### Basic Link Navigation Source: https://github.com/strblr/typeroute/blob/master/README.md Use the Link component to navigate to a route pattern string or a route object. This is the most basic usage for navigating between pages. ```tsx About About ``` -------------------------------- ### useParams(route) Source: https://github.com/strblr/typeroute/blob/master/README.md Returns typed path parameters for a given route. ```APIDOC ## useParams(route) ### Description Returns typed path parameters for a given route. ### Parameters #### Path Parameters - **route** (`Pattern | Route`) - A route pattern string or route object. ### Returns `Params` - The extracted path params, fully typed. ### Example ```tsx const { id } = useParams(userRoute); ``` ``` -------------------------------- ### Programmatic route preloading Source: https://github.com/strblr/typeroute/blob/master/README.md Preload routes programmatically using the `router.preload()` method. This allows for preloading based on specific application logic or events. ```typescript const router = useRouter(); router.preload({ to: userProfile, params: { id: "42" } }); ``` -------------------------------- ### Route.lazy(loader) Source: https://github.com/strblr/typeroute/blob/master/README.md Configures a lazy-loaded component for the route. The component is loaded asynchronously only when the route matches. ```APIDOC ## Route.lazy(loader) ### Description Configures a lazy-loaded component for the route. The component is loaded asynchronously only when the route matches. ### Parameters #### Path Parameters - **loader** (ComponentLoader) - Required - A function returning a dynamic import promise ### Returns - **Route** - A new route object ``` -------------------------------- ### history.push(options) Source: https://github.com/strblr/typeroute/blob/master/README.md Pushes a new entry onto the history stack or replaces the current one. ```APIDOC ## history.push(options) ### Description Pushes or replaces a history entry. ### Parameters - `options` - `HistoryPushOptions` - The URL to navigate to, with optional `replace` and `state`. ### Returns - `void` ### Usage Example ```tsx history.push({ url: "/users/42", state: { from: "list" } }); history.push({ url: "/login", replace: true }); ``` ``` -------------------------------- ### history.go(delta) Source: https://github.com/strblr/typeroute/blob/master/README.md Navigates forward or backward in the history stack by a specified number of entries. ```APIDOC ## history.go(delta) ### Description Navigates forward or back in history. ### Parameters - `delta` - `number` - The number of entries to move. ### Returns - `void` ### Usage Example ```tsx history.go(-1); // Go back history.go(1); // Go forward history.go(-2); // Go back two steps ``` ``` -------------------------------- ### router.navigate Source: https://github.com/strblr/typeroute/blob/master/README.md Navigates to a new location within the application. Supports type-safe navigation using route parameters, untyped URL navigation, and history manipulation (back/forward). ```APIDOC ## `router.navigate(options)` Navigates to a new location. - `options` - `NavigateOptions | HistoryPushOptions | number` - Type-safe navigation options, untyped navigation options, or a history delta - Returns: `void` ```tsx // Type-safe navigation router.navigate({ to: "/posts/:id", params: { id: "42" } }); // Untyped navigation router.navigate({ url: "/any/path" }); // History navigation router.navigate(-1); // Back router.navigate(1); // Forward ``` ``` -------------------------------- ### RouterRoot Component Usage Source: https://github.com/strblr/typeroute/blob/master/README.md Use RouterRoot to set up routing context. It accepts either router options or a router instance. ```tsx ``` -------------------------------- ### History Middleware for View Transitions Source: https://github.com/strblr/typeroute/blob/master/README.md Wrap navigation actions in a view transition using the browser's View Transitions API. This middleware ensures smoother page animations. ```tsx import { flushSync } from "react-dom"; import { BrowserHistory, type HistoryLike } from "@typeroute/router"; const withViewTransition = (history: HistoryLike) => { const { go, push } = history; const wrap = (fn: () => void) => { return !document.startViewTransition ? fn() : document.startViewTransition(() => flushSync(fn)); }; history.go = delta => wrap(() => go(delta)); history.push = options => wrap(() => push(options)); return history; }; const history = withViewTransition(new BrowserHistory()); function App() { return ; } ``` -------------------------------- ### Push or Replace History Entry with history.push() Source: https://github.com/strblr/typeroute/blob/master/README.md The history.push() method allows you to navigate to a new URL, optionally replacing the current entry or passing state. ```tsx history.push({ url: "/users/42", state: { from: "list" } }); history.push({ url: "/login", replace: true }); ``` -------------------------------- ### Apply Multiple Middlewares to a Route Source: https://github.com/strblr/typeroute/blob/master/README.md A single route can utilize multiple middlewares by chaining the `.use()` method. This allows for combining different configurations. ```typescript route("/users").use(auth).use(pagination).component(UserPage); ``` -------------------------------- ### Preload Route Resources Source: https://github.com/strblr/typeroute/blob/master/README.md Trigger preloading for a specified route. This is useful for optimizing performance by fetching necessary resources ahead of time. ```tsx await router.preload({ to: "/user/:id", params: { id: "42" } }); await router.preload({ to: searchPage, search: { q: "test" } }); ``` -------------------------------- ### Link with 'viewport' preload strategy Source: https://github.com/strblr/typeroute/blob/master/README.md Use 'viewport' with an Intersection Observer to preload when the link scrolls into view. This is effective for links further down the page or on mobile devices. ```tsx See more ``` -------------------------------- ### Unordered Route Definitions Source: https://github.com/strblr/typeroute/blob/master/README.md Demonstrates that the order of route definitions does not affect TypeRoute's matching accuracy due to its ranking algorithm. ```tsx const routes = [ route("/posts/*").component(NotFound), route("/posts/:id").component(PostPage), route("/posts/new").component(NewPost) ]; // Order doesn't matter ``` -------------------------------- ### RouterOptions Type Definition Source: https://github.com/strblr/typeroute/blob/master/README.md Defines the configuration options for creating a Router instance or passing to RouterRoot. It includes route definitions, base path, history implementation, and context. ```typescript type RouterOptions = { routes: Route[] | Record; // Collection of navigable routes basePath?: string; // Base path prefix (default: "/") history?: HistoryLike; // History implementation (default: BrowserHistory) context?: Context; // Arbitrary router context ssrContext?: SSRContext; // Context for server-side rendering defaultLinkOptions?: LinkOptions; // Default options for all Link components }; ``` -------------------------------- ### Route.index(component) Source: https://github.com/strblr/typeroute/blob/master/README.md Sets a fallback component to be rendered when no other outlet content is available for the current route. ```APIDOC ## Route.index(component) ### Description Sets a fallback component to be rendered when no other outlet content is available for the current route. ### Parameters #### Path Parameters - **component** (ComponentType) - Required - A React component ### Returns - **Route** - A new route object ``` -------------------------------- ### Basic Not-Found Page Component Source: https://github.com/strblr/typeroute/blob/master/README.md A simple React component for a 404 page, including a link back to the home page. ```tsx function NotFoundPage() { return (

404

This page doesn't exist.

Go home
); } ``` -------------------------------- ### Define Routes with Dynamic Segments Source: https://github.com/strblr/typeroute/blob/master/README.md Define routes with dynamic segments (path parameters) using the `:param` syntax. Supports required, nested, and optional dynamic segments. ```tsx const required = route("/posts/:id"); const nested = route("/org/:orgId/team/:teamId"); const optional = route("/book/:title?"); ``` -------------------------------- ### Styling Active Links with Props Source: https://github.com/strblr/typeroute/blob/master/README.md Alternatively, use the `activeClassName` and `activeStyle` props for direct styling of active links. This offers a programmatic approach to styling active states. ```tsx Dashboard ``` -------------------------------- ### PreloadOptions Interface Definition Source: https://github.com/strblr/typeroute/blob/master/README.md Options object passed to functions responsible for preloading route data. Includes path parameters, search parameters, and router context. ```typescript interface PreloadOptions { params: Params; // Path params for the route search: Search; // Validated search params context: Context; // Router context } ``` -------------------------------- ### Defining a Catch-All Not-Found Route Source: https://github.com/strblr/typeroute/blob/master/README.md A catch-all route '/*' with the lowest weight naturally acts as a fallback. It matches only when no other route does. ```tsx const home = route("/").component(HomePage); const notFound = route("/*").component(NotFoundPage); const about = route("/about").component(AboutPage); const routes = [home, notFound, about]; ``` -------------------------------- ### history.subscribe(listener) Source: https://github.com/strblr/typeroute/blob/master/README.md Subscribes a listener function to be called on navigation events. ```APIDOC ## history.subscribe(listener) ### Description Subscribes to navigation events. ### Parameters - `listener` - `() => void` - Callback invoked when any navigation occurs. ### Returns - `() => void` - An unsubscribe function. ### Usage Example ```tsx const unsubscribe = history.subscribe(() => { console.log("Navigation occurred"); }); // Later: unsubscribe() ``` ``` -------------------------------- ### Link Component Source: https://github.com/strblr/typeroute/blob/master/README.md Renders an anchor tag for navigation, supporting various navigation and link options. ```APIDOC ## Link Component ### Description Renders an anchor tag for navigation. ### Props - `props` - `NavigateOptions & LinkOptions & { asChild?: boolean }` - Navigation options, link options, and optional `asChild` to use a child element as the anchor; other props are passed through. ### Usage Example ```tsx Click me ``` ``` -------------------------------- ### Create Parametrized Middlewares Source: https://github.com/strblr/typeroute/blob/master/README.md Define middlewares as functions that accept parameters to create dynamic and reusable middleware configurations. ```typescript const guard = (role: string) => middleware().handle({ requiredRole: role }).component(RoleGuard); const adminPage = route("/admin").use(guard("admin")).component(AdminPage); const editorPage = route("/editor").use(guard("editor")).component(EditorPage); ``` -------------------------------- ### HashHistory Source: https://github.com/strblr/typeroute/blob/master/README.md History implementation using the URL hash. ```APIDOC ## HashHistory ### Description URL hash implementation for navigation. ### Usage ```tsx new HashHistory(); ``` ``` -------------------------------- ### Route.component(component) Source: https://github.com/strblr/typeroute/blob/master/README.md Associates a React component with the route, which will be rendered when the route matches. ```APIDOC ## Route.component(component) ### Description Associates a React component with the route, which will be rendered when the route matches. ### Parameters #### Path Parameters - **component** (ComponentType) - Required - A React component ### Returns - **Route** - A new route object ``` -------------------------------- ### Access Route Handles with useHandles Source: https://github.com/strblr/typeroute/blob/master/README.md Access all handles for the current route match using the `useHandles()` hook. This hook returns handles in the order they were added. ```tsx function Breadcrumbs() { const handles = useHandles(); return ( ); } ``` -------------------------------- ### BrowserHistory Source: https://github.com/strblr/typeroute/blob/master/README.md History implementation using the Browser History API. ```APIDOC ## BrowserHistory ### Description Browser History API implementation for navigation. ### Usage ```tsx new BrowserHistory(); // Default. ``` ``` -------------------------------- ### Find the Best Route Match for a Path Source: https://github.com/strblr/typeroute/blob/master/README.md Find the best matching route for a given path from all registered routes. Returns the match details or null if no route matches. ```tsx const match = router.matchAll("/users/42"); // Returns the best match or null ``` -------------------------------- ### Multi-level Route Derivation Source: https://github.com/strblr/typeroute/blob/master/README.md Demonstrates building deeply nested routes by deriving from a shared base route. Each level must include an Outlet for rendering the subsequent component. ```tsx const app = route("/").component(AppShell); const dashboard = app.route("/dashboard").component(DashboardLayout); const settings = dashboard.route("/settings").component(SettingsLayout); const security = settings.route("/security").component(SecurityPage); ``` -------------------------------- ### Navigate Component with Options Source: https://github.com/strblr/typeroute/blob/master/README.md The Navigate component accepts the same navigation props as the Link component, including 'to', 'params', 'search', 'replace', and 'state'. ```tsx ``` -------------------------------- ### Update Search Params Source: https://github.com/strblr/typeroute/blob/master/README.md Demonstrates how to update search parameters using the setter function returned by `useSearch`. Updates can be partial or based on previous values. ```tsx setSearch({ page: 2 }); // Only updates page setSearch(prev => ({ page: prev.page + 1 })); // Increment page ``` -------------------------------- ### Using Link with Custom Component (asChild) Source: https://github.com/strblr/typeroute/blob/master/README.md The `asChild` prop enables using your own component as the anchor while retaining Link's navigation behavior. This provides flexibility in styling and structure. ```tsx Go to profile ``` -------------------------------- ### Navigate History with history.go(delta) Source: https://github.com/strblr/typeroute/blob/master/README.md Use history.go() to navigate forward or backward in the browser's history stack by a specified number of entries. ```tsx history.go(-1); // Go back history.go(1); // Go forward history.go(-2); // Go back two steps ``` -------------------------------- ### Define Typed Path Parameters Source: https://github.com/strblr/typeroute/blob/master/README.md Define dynamic segments in route patterns with a colon prefix. These segments become typed path parameters. ```tsx const post = route("/posts/:id").component(PostPage); const comment = route("/posts/:postId/comments/:commentId?").component( CommentPage ); ``` -------------------------------- ### router.match Source: https://github.com/strblr/typeroute/blob/master/README.md Checks if a given path matches a specific route pattern, returning detailed match information including route and extracted parameters. ```APIDOC ## `router.match(path, options)` Checks if a path matches a specific route. - `path` - `string` - The path to match against - `options` - `MatchOptions` - Matching options - Returns: `Match | null` - The match result or null if no match ```tsx const match = router.match("/users/42", { from: "/users/:id" }); // Returns { route, params: { id: "42" } } ``` ``` -------------------------------- ### Route.error(fallback) Source: https://github.com/strblr/typeroute/blob/master/README.md Wraps subsequent route components in an error boundary, providing a fallback UI in case of rendering errors. ```APIDOC ## Route.error(fallback) ### Description Wraps subsequent route components in an error boundary, providing a fallback UI in case of rendering errors. ### Parameters #### Path Parameters - **fallback** (ComponentType<{ error: unknown }>) - Required - The fallback component, receives the caught error as a prop ### Returns - **Route** - A new route object ``` -------------------------------- ### Check Route Match Source: https://github.com/strblr/typeroute/blob/master/README.md Determines if a route matches the current URL based on provided options. Supports strict matching and parameter filtering. ```tsx const match = useMatch({ from: "/users/:id" }); const strictMatch = useMatch({ from: "/users", strict: true }); const filteredMatch = useMatch({ from: "/users/:id", params: { id: "admin" } }); ```