Routes and navigation#
@zidomjs/router is an optional client-side browser router supporting static segments, route parameters, wildcard paths, nested routes, guards and asynchronous loaders.
import { createRouter, type Route } from '@zidomjs/router';type Context = { signedIn: boolean };const context: Context = { signedIn: false };const routes: Route<Context>[] = [ { path: '/', component: () => <h1>Home</h1> }, { path: '/users/:id', component: ({ params }) => <h1>{params.id}</h1> }, { path: '*', component: () => <h1>Not found</h1> }];const router = createRouter({ context, routes });const dispose = router.mount(document.getElementById('app')!);await router.navigate('/users/42');pathname, pending, and error expose readonly signals. Navigation is integrated with browser history; navigate(path, { replace: true }) replaces the current entry.
Guards and authorization#
import { createRouter, requireAuth, type Route } from '@zidomjs/router';const context = { signedIn: false };const routes: Route<typeof context>[] = [ { path: '/login', component: () => <h1>Log in</h1> }, { path: '/dashboard', beforeLoad: requireAuth({ isAuthenticated: ctx => ctx.signedIn }), component: () => <h1>Dashboard</h1> }];createRouter({ context, routes });Guards run before loaders and views. requireAuth defaults to redirecting to /login?returnTo=...; requirePermission can route to /forbidden.
Async loaders and cancellation#
const users: Route<Context> = { path: '/users/:id', load: async ({ params, signal }) => { const response = await fetch(`/api/users/${params.id}`, { signal }); if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.json(); }, component: ({ data }) => <pre>{JSON.stringify(data)}</pre>};The router provides an AbortSignal, and superseded navigation results are ignored. It now stages the next view before committing history, reducing broken navigation when a destination fails to render.
Limits#
Route-path-to-type inference, persistent layout reuse, dedicated route error boundaries, built-in scroll restoration and SSR router support are not shipped. Browse router source for the latest details.
Run the example#
Open the interactive router example. Try navigating in the preview first, then switch among router.tsx, router-home.tsx and router-profile.tsx to inspect the router setup and each actual page component. Lines wrap within the code panel on narrow screens; the Copy button preserves the original source.