Routing

Client-side navigation with dynamic params, nested layouts, middleware, and view transitions.

Basic Setup

Define your routes and render the Router component. Each route maps a URL path to a component:

import { mount } from 'what-framework';
import { Router, defineRoutes } from 'what-framework/router';

import Home from './pages/Home';
import About from './pages/About';
import NotFound from './pages/NotFound';

const routes = defineRoutes({
  '/': Home,
  '/about': About,
});

mount(
  <Router routes={routes} fallback={NotFound} />,
  '#app'
);

defineRoutes accepts a plain object where keys are URL paths and values are components. The fallback prop renders when no route matches (404).

Use Link for client-side navigation. It intercepts clicks, updates the URL via history.pushState, and re-renders the router without a full page reload:

import { Link } from 'what-framework/router';

function Nav() {
  return (
    <nav>
      <Link href="/">Home</Link>
      <Link href="/about">About</Link>
      <Link href="/blog">Blog</Link>
    </nav>
  );
}

Link automatically adds an active class when the current path is the href or one of its sub-paths (/ is the exception: it is active only on /). When the path and the href are identical it also adds exact-active:

<nav>
  {/* Customize active class names */}
  <Link href="/blog" activeClass="nav-active" exactActiveClass="nav-exact">
    Blog
  </Link>

  {/* Replace history entry instead of pushing */}
  <Link href="/login" replace>Sign In</Link>
</nav>

Programmatic Navigation

Use navigate() to change routes from event handlers or effects:

import { navigate } from 'what-framework/router';

function LoginForm() {
  async function handleSubmit(e) {
    e.preventDefault();
    await login(email, password);
    navigate('/dashboard');
  }

  return <form onSubmit={handleSubmit}>...</form>;
}

// Options
navigate('/settings', { replace: true });   // Replace history entry
navigate('/profile', { state: { from: 'nav' } }); // Pass state
navigate('/page', { transition: false });     // Skip view transition
navigate('/page', { flushSync: true });      // Commit at once
navigate('/settings#teams');                  // On /settings: a fragment navigation
navigate('https://example.com/docs');         // Another origin: the browser loads it

A navigation is a transition. navigate() and <Link> run the beforeNavigate guards, then prepare the destination while the old page stays on screen: they load a lazy() route's chunk and run its preload, and wait for both. Then the URL commits inside startTransition, so the page and everything else the new URL reaches (a layout's data keyed on the params) commit in one flush. navigate() resolves once the new page is on screen and the data it reads first has landed, and a newer navigation supersedes one still preparing. route.isNavigating is true meanwhile, and useTransition's isPending around a navigate() call is true until the commit.

A URL of another origin (another site, mailto:, tel:) is the browser's to load, as a click on a <Link> to it is: navigate() calls location.assign(), or location.replace() with replace: true, and runs no guard. A middleware or redirect() that sends a navigation to another origin replaces the entry the same way.

A navigation that changes only the hash (navigate('#teams'), or navigate('/settings#teams') while on /settings, a <Link> to either, the browser moving the hash with back/forward or location.hash) is a fragment navigation, as in the browser: the page stays mounted with its state, the URL and route.hash move, and the element with that id scrolls into view. No guard, middleware or preload runs, and beforeNavigate and afterNavigate are not called. A '#hash' target replaces the history entry; a path with a hash adds one unless replace: true.

Route Data: preload

A route's preload({ params, query, url }) starts the data the page needs. The navigation waits for what it returns (a query(), an async value, a promise, or an array or object of them), and the page receives it as its data prop:

import { Router } from 'what-framework/router';
import { query } from 'what-framework/data';

const user = (id) => query(['user', id], (key, { signal }) => fetch(`/api/users/${key[1]}`, { signal }).then((r) => r.json()), { staleTime: 30_000 });

const routes = [
  {
    path: '/users/:id',
    preload: ({ params }) => user(params.id),
    component: ({ data }) => <h1>{data().name}</h1>,
  },
];

export const App = () => <Router routes={routes} />;

A query() the page makes on the same key is answered from the cache. The queries a preload makes are read on the route's path, so invalidatePath('/users/7'), which a server action's revalidate calls, refetches them inside the action's transition.

Data the page reads that preload does not return is fetched after the URL commits: the page shows it pending (its bindings hold, or its <Suspense> shows its fallback), and the navigation goes on until it has landed. Only preload data keeps the old page on screen, so return what the page needs at once from it.

The route Object

Access the current route state from anywhere in your app using the reactive route object:

import { route } from 'what-framework/router';

// All properties are reactive getters
route.path     // "/users/42"
route.params   // { id: "42" }
route.query    // { tab: "posts" }; ?tag=a&tag=b gives { tag: ["a", "b"] }
route.hash     // "#section"
route.isNavigating  // true from navigate() until the new page's first data has landed

No Parentheses Needed

route.path, route.params, etc. are property getters that internally read signals. You access them like normal properties, with no () call needed. They are still reactive: JSX, an effect or a thunk that reads one updates when the route changes, with no re-render involved.

route.query is a null-prototype object, so a crafted query string cannot reach Object.prototype. Reading, destructuring, spreading, Object.keys() and JSON.stringify() all behave normally, but inherited members are gone: use 'tab' in route.query or Object.prototype.hasOwnProperty.call(route.query, 'tab') rather than route.query.hasOwnProperty('tab'). A repeated key collects into an array, so ?tag=a&tag=b gives { tag: ["a", "b"] }. Its TypeScript type is RouteQuery, Record<string, string | string[]> (exported by what-framework/router), so narrow a value before using it as a string.

Dynamic Params

Use :param syntax in route paths to capture dynamic segments. The matched values are passed to your component as params:

const routes = defineRoutes({
  '/': Home,
  '/users/:id': UserProfile,
  '/posts/:slug': BlogPost,
  '/files/*': FileViewer,          // Catch-all: params.rest
  '/docs/[...path]': DocsPage,     // Named catch-all
});

function UserProfile({ params }) {
  return <h1>User #{params.id}</h1>;
}

function DocsPage({ params }) {
  return <p>Path: {params.path}</p>;  // "guides/getting-started"
}

File-based syntax like [id] and [...path] also works: it's converted to :id and catch-all internally.

A trailing slash is ignored when matching, except on the root: /about/ shows the route /about (a static host serves about/index.html there), and route.path keeps the slash as the address bar has it. A link is active the same way, so <Link href="/docs/"> is active on /docs and below it. A server render matches a request the same way.

Nested Layouts

Wrap groups of routes in shared layouts. The layout component receives the matched route's element as children:

import { Link, nestedRoutes } from 'what-framework/router';

function DashboardLayout({ children }) {
  return (
    <div class="dashboard">
      <aside>
        <Link href="/dashboard">Overview</Link>
        <Link href="/dashboard/settings">Settings</Link>
      </aside>
      <main>{children}</main>
    </div>
  );
}

const routes = [
  { path: '/', component: Home },
  ...nestedRoutes('/dashboard', [
    { path: '/', component: DashboardHome },
    { path: '/settings', component: Settings },
    { path: '/users/:id', component: UserDetail },
  ], { layout: DashboardLayout }),
];

Route Guards & Middleware

Route middleware runs synchronously with { path, url, params, query, route }, where url is the whole destination (path, search and hash) and route is the destination's route config. Returning nothing also allows the route. Promises are not awaited: use asyncGuard() for asynchronous checks. Middleware runs before the route's preload, which never runs for a route it declines. It runs once for a navigation, whose verdict the page renders by, and again only when a signal it read changes. On the server, a middleware redirect redirects the render's response. The TypeScript middleware declaration now reflects this runtime contract; older declarations incorrectly accepted Promise<boolean>.

Protect routes with middleware functions that run before the route renders. Middleware can allow, reject, or redirect:

import { guard } from 'what-framework/router';

// Sync guard: redirect if not authenticated
const requireAuth = guard(
  () => isLoggedIn(),
  '/login'           // Redirect path on failure
);

const ProtectedDashboard = requireAuth(Dashboard);

// Or use middleware in route config
const routes = defineRoutes({
  '/dashboard': {
    component: Dashboard,
    middleware: [
      ({ path, params }) => {
        if (!isLoggedIn()) return '/login'; // Redirect
        if (!isAdmin()) return false;      // Block
        return true;                       // Allow
      }
    ],
  },
});

The two shapes are not interchangeable. guard() and asyncGuard() wrap a component and hand back a new one, so their result belongs in component:. Entries in a middleware array are predicates called with the match context: return true to allow, a path string to redirect, or false to block. Blocking renders the Router's fallback component when one is set (the same component your 404s use) and a built-in 403 screen when it is not, so redirect to a dedicated route if you need to tell the two apart.

For async checks (like verifying a session with the server), use asyncGuard:

import { asyncGuard } from 'what-framework/router';

const requireSession = asyncGuard(
  async () => {
    const res = await fetch('/api/session');
    return res.ok;
  },
  { fallback: '/login', loading: Spinner }
);

// asyncGuard returns a wrapper, so apply it to the component
const ProtectedSettings = requireSession(Settings);

Route Groups

Apply one layout and one middleware list to a set of routes. routeGroup never touches the paths, so write each URL out in full; the group name is a label for your own code:

import { routeGroup } from 'what-framework/router';

const routes = [
  ...routeGroup('marketing', [
    { path: '/', component: Home },
    { path: '/about', component: About },
    { path: '/pricing', component: Pricing },
  ], { layout: MarketingLayout }),

  ...routeGroup('app', [
    { path: '/dashboard', component: Dashboard },
    { path: '/settings', component: Settings },
  ], { layout: AppLayout, middleware: [() => isLoggedIn() || '/login'] }),
];

Loading & Error States

Specify per-route loading and error components:

const routes = defineRoutes({
  '/dashboard': {
    component: Dashboard,
    loading: DashboardSkeleton,  // Shown while a navigation is pending
    error: DashboardError,       // Shown on render error
  },
});

Without a loading component, the page being left stays on screen while a navigation prepares. With one, the loading component renders instead while the navigation prepares. asyncGuard never sets that flag, so a route it protects shows the guard's own loading option while the check is pending, never the route's. When both the route being left and the route being entered declare a loading component, the destination's wins.

The error component is wrapped in an ErrorBoundary that catches exceptions during rendering. It is called with { error, reset }, and reset re-runs the failed subtree:

function DashboardError({ error, reset }) {
  return (
    <div class="route-error">
      <p>{error.message}</p>
      <button onClick={reset}>Retry</button>
    </div>
  );
}

View Transitions

What Router uses the browser's View Transitions API by default for smooth page transitions. The update callback is the navigation's commit, after the destination was prepared, so the browser captures the new page once it is on screen. No configuration needed, just add CSS:

/* Fade in/out by default */
::view-transition-old(root) {
  animation: fade-out 150ms ease-out;
}
::view-transition-new(root) {
  animation: fade-in 150ms ease-in;
}

@keyframes fade-out { to { opacity: 0; } }
@keyframes fade-in { from { opacity: 0; } }

Name specific elements for independent transitions:

import { viewTransitionName } from 'what-framework/router';

function Card({ id, title }) {
  return (
    <div {...viewTransitionName(`card-${id}`)}>
      <h2>{title}</h2>
    </div>
  );
}

Scroll Restoration

The router already saves the scroll position on every navigation and restores it on back/forward, with no setup. enableScrollRestoration() applies three rules to ordinary forward navigations as well, checked in this order:

import { enableScrollRestoration } from 'what-framework/router';

enableScrollRestoration();
// 1. Hash links scroll to the target element
// 2. Returning to a URL you already scrolled restores that position
// 3. Everything else scrolls to top

The order matters. A URL carrying a hash always goes to its element, even when a position is saved for that exact URL, so clicking the same #install link twice lands on the section both times. Positions are keyed by the full URL, path and query and hash together, so /list?tab=inbox and /list?tab=archive each remember their own place. These rules are for forward navigations: back and forward land where the entry was left, as the browser restores one, at the position saved for it and not at its hash element first.

Rule 2 is the one that surprises people: a nav-bar link back to a page you scrolled earlier in the session lands where you left it rather than at the top, and switching back to a tab you have already opened does the same. Saved positions live in memory for the life of the page, so a reload starts clean and the browser's own history.scrollRestoration takes over.

Prefetching

Link components prefetch on hover by default. You can also prefetch programmatically:

import { prefetch } from 'what-framework/router';

// Appends <link rel="prefetch"> for this URL
prefetch('/dashboard');

// Disable prefetch on a specific Link
<Link href="/heavy-page" prefetch={false}>Heavy Page</Link>

Prefetching starts downloading the lazy() chunk of the route the URL goes to, so the click need not wait for it, unless that route has middleware (a navigation downloads it once the middleware admits it). It also hints the browser to fetch the URL. Each URL is prefetched at most once per page load.

Serving Below a Base Path

An app deployed below a path (/app/ on GitHub Pages or behind a reverse proxy) routes below it. With Vite, its base is the router's: set base: '/app/' in vite.config.js. A server-rendered app gives what-server the same path, createRequestHandler({ basePath: '/app' }) or exportStatic({ basePath: '/app' }), and the router renders the pages they serve below it, with no setBase on the server, also in a server build that keeps what-router external. Without Vite's base (another bundler), or in a custom server that renders with renderToString, call setBase once, before the app renders:

import { setBase } from 'what-framework/router';

setBase('/app'); // or setBase(import.meta.env.BASE_URL)

Below the base, a path from the root is a URL of the app: <Link href="/x"> renders and goes to /app/x, navigate('/x'), redirect('/x') and a middleware returning '/x' go to /app/x, and route paths are written as without a base. Route state holds the URL without the base: route.url, route.path, the params, useRoute(), active links, and what middleware, preload and the navigation hooks are given. A relative href resolves against the address bar, as the browser resolves it. A URL outside the base is not the app's: no route shows it (a catch-all included: the Router shows its fallback), and navigate() and <Link> leave it to the browser. A server render of a request below the base renders the same page, and its redirects go below the base: a path is a URL of the app whoever redirects to it, so a loader's response.redirect('/login') and a component's getResponse().redirect('/login') answer /app/login, as redirect('/login') does. '/app', '/app/' and 'app' are the same base; '' and '/' are none. A base the app sets (Vite's, setBase) is the router's on the server too; give what-server's basePath the same path. Server actions use the same base: an action posts to /app/__what_action, a <Form>'s redirect is a URL of the app, and so is a path an action redirects to.

useRoute Hook

Access reactive route state inside any component with the useRoute hook. Returns computed signals for each property:

import { useRoute } from 'what-framework/router';

function Breadcrumbs() {
  const { path, params, query, navigate } = useRoute();

  return (
    <nav class="breadcrumbs">
      <span>You are at: {path()}</span>
    </nav>
  );
}

route vs useRoute

The global route object uses property getters (route.path) while useRoute() returns computed signals (path()). Both are reactive. Use route for quick access, useRoute when you want to destructure or pass around individual properties.