Skip to content

Typed routing ​

@hedystia/router provides typed code routes and generated lazy file routes for View. It reuses Hedystia Query for loader ownership and caching instead of bundling an external routing library.

sh
npm install @hedystia/router

Define and mount routes ​

tsx
import { createLayout, createRoute, createRouter } from "@hedystia/router";

const product = createRoute("/products/$id", {
  validateSearch: (raw) => {
    const page = Number(raw.page ?? 1);
    if (!Number.isInteger(page) || page < 1) throw new Error("Invalid page");
    return { page };
  },
  loader: async ({ params, search, signal }) => {
    const response = await fetch(`/api/products/${encodeURIComponent(params.id)}?page=${search.page}`, { signal });
    if (!response.ok) throw new Error(`Request failed: ${response.status}`);
    return response.json() as Promise<{ id: string; name: string }>;
  },
  component: ({ data }) => <h1>{() => data().name}</h1>,
});

const root = createLayout("root", {
  component: ({ outlet }) => <main>{outlet}</main>,
}).addChildren([
  createRoute("/", { component: () => <h1>Home</h1> }),
  product,
]);

const router = createRouter({ routes: [root], viewTransitions: true });
const app = router.mount(document.getElementById("app")!);

Configure JSX as described in View setup. Route components receive reactive params(), search() and data() accessors, plus an outlet accessor. Shared layouts keep their DOM and reactive owner while child routes change. Use accessors inside JSX for values that should update. Call app.dispose() when removing the application.

tsx
await router.navigate({
  to: "/products/$id",
  params: { id: 42 },
  search: { page: 2 },
});

const href = router.href({ to: "/products/$id", params: { id: 42 } });
const link = router.Link({
  to: "/products/$id",
  params: { id: 42 },
  children: "Product 42",
  activeClass: "active",
});

const productData = router.match("/products/$id")?.data;

Unknown destinations, missing params and wrong validated search values are type errors. Params are encoded independently and decoded into strings for loaders. Normal params cannot be empty, . or ..; a final $ route segment captures a slash-separated _splat value.

Link remains a real anchor, works in static HTML, and preloads on hover/focus intent after a short cancellable delay. Set preload: false to disable intent loading. Modified clicks, downloads, non-self targets and external URLs retain native behavior. A data-router-ignore attribute on a manually authored anchor opts out of interception.

File routes and automatic types ​

ts
import { defineConfig } from "vite";
import { viewPlugin } from "@hedystia/view/vite";
import { routerPlugin } from "@hedystia/router/vite";

export default defineConfig({
  plugins: [...viewPlugin().plugins, routerPlugin()],
});

Create src/routes/products/$id.tsx:

tsx
import { createRoute } from "@hedystia/router";

export const Route = createRoute("/products/$id", {
  loader: ({ params }) => ({ id: params.id }),
  component: ({ data }) => <h1>Product {() => data().id}</h1>,
});

Then use the generated tree:

ts
import { createRouter } from "@hedystia/router";
import { routeTree } from "./routeTree.gen";

export const router = createRouter({ routes: routeTree });

__root.tsx supplies a pathless root layout. Nested _layout.tsx files provide uniquely named pathless layouts. index.tsx maps to /; products/index.tsx maps to /products/, under a /products parent when present. Dotted route names are supported. Prefix ignored files with -; test, spec and declaration files are excluded.

The plugin generates deterministic lazy imports before builds and when route files are added or removed. It exports FileRoutePath as well as the inferred tree. Filename and declared-path mismatches fail compilation. It refuses to overwrite a handwritten output file. You can call generateRoutes() from @hedystia/router/vite before running TypeScript independently. Type inference supports twelve nested route-definition levels.

Loader lifecycle and caching ​

Matching and synchronous search validation precede serial parent-to-child beforeLoad guards. Component imports and loader work can then proceed concurrently. Loaders receive { params, search, signal, preload }; forward the signal to your typed HTTP client or native fetch.

Cache identity includes route ID, params and validated search. loaderDeps(search) can select only the search fields that affect data. Dependencies use Query's finite JSON-key contract. Preloading and navigation share requests without aborting work another consumer still owns, and obsolete navigation cannot overwrite the current page.

Navigation defaults to staleTime: 0; preloading defaults to preloadStaleTime: 30000. Set either on a route or the router. Fresh preloaded data is reused for the next navigation. There is no automatic polling or timer-based garbage collection; inactive cache retention is bounded by Query. Use router.invalidate() after mutations to clear loader data and reload the current location.

Guards and outcomes ​

Throw redirect("/login") from a guard to navigate internally. Throw notFound() from a loader for a missing resource. Other failures select the nearest route errorComponent, or the router's generic fallback. Error handlers receive error and retry. Router-level pendingComponent and notFoundComponent handle initial loading and missing pages. Existing committed content remains visible while a new route loads.

Redirects cannot leave the configured origin/base path and are limited to ten hops. router.state() exposes loading status and generic match metadata; use router.match(path) or component accessors for route-specific data types.

History, transitions and SSR ​

The mounted router owns its root's links and browser history listeners. It restores scroll by history entry, supports hash targets, and focuses an explicit [data-router-focus] element, heading or main element after navigation. resetScroll: false preserves position. viewTransitions: true opts into native document.startViewTransition with a fallback and reduced-motion support.

On the server, create a router per request, set initialUrl to the request URL, await router.load(), and render RouterView using View's server renderer. Do not reuse personalized loader caches across requests.

For Astro, use Astro page routes and optional ClientRouter for the document, or mount a View router inside an explicit interactive island. Do not let both intercept the same root. Static Astro pages can use typed href values without shipping SPA routing JavaScript.

This package borrows core patterns from TanStack Router but does not implement every TanStack feature. Relative from navigation, optional path syntax, automatic parent search/context inheritance, deferred streaming, global route registration and devtools are outside this implementation.

Cancelling navigation restores the last committed state and clears the mounted root’s busy indicator. Invalid external destinations are rejected before they can cancel an existing navigation.