Skip to content
@pyreon/router
core · routing

Every navigation runs your guards. The Back button too.

Nested routes, loaders that finish before the page renders, guards, middleware and leave blockers, and await router.push() tells you whether the navigation committed, was cancelled or was superseded. The same route table runs in the browser, on the server and in the experimental iOS and Android builds.

bun add @pyreon/router
Documentation
matching
885–3,763× React RouterLevel with radix3 at 50 and 200 routes. One run, synthetic, author-run.
push() returns
committed · cancelled · superseded
accessibility
page changes announcedThe root <RouterView> speaks each new title to screen readers.
native
routes, guards and deep links on iOS and AndroidNative targets are experimental.
A navigation passes guard and loader before the view renders The address bar changes from / to /user/42. The route /user/:id matches, its beforeEnter guard passes, its loader runs, and the view renders with useParams() typed as { id: string } holding '42' and its loader data ready. Then the address returns to / and the home route renders. @PYREON/ROUTER · ONE NAVIGATION example.com/ example.com/user/42 router.push() routes '/''/' '/user/:id''/user/:id' '/settings' '*' notFound beforeEnterguard ✓ loaderbefore render ✓ view transition <Home /> <User /> useParams() { id: '42' } useLoaderData()() { name: … } '/user/:id' → params: { id: string }, typed from the path await router.push() resolves once the new view is in place
  • 885× faster route matching than React Router, and up to 3,763× (8 routers, 1,344-cell correctness gate before timing)BENCHMARKS.md 2026-11-05 §9, final pass, one run
  • 7.7–19× faster matching than Vue Router, and 7.7–8.3× faster than TanStack RouterBENCHMARKS.md 2026-11-05 §9, one run
  • 1.00× the best average at 50 routes, a tie with radix3 (1.01×), the fastest standalone matcherBENCHMARKS.md 2026-11-05 §9, one run, no CI on the average row

synthetic · author-run · M3 Max · record of 2026-11-05

Every result, including where we lose →
why teams pick it

Routing with fewer ways to get it wrong.

  1. The Back button runs the pipeline

    Back and Forward go through blockers, middleware, guards and loaders like any push(). Sign out, press Back to a guarded page, and you land on /login. If a guard cancels, the URL and history position are restored.

  2. Data before the page

    Loaders run in parallel before the route commits and get an AbortSignal when a newer navigation supersedes them. useLoaderData<LoaderData<typeof loader>>() takes its type from the loader, so the two can't drift.

  3. Navigation that reports back

    await router.push('/checkout') resolves to 'committed', 'cancelled' (a blocker, guard or middleware said no) or 'superseded' (a newer navigation won). No guessing from the URL afterwards.

  4. Accessible by default

    The root <RouterView> announces each new page through a polite live region. View Transitions are one option away (viewTransition: true), and skip the animation when the user asks for reduced motion.

the difference

A signed-in area: the guard is a guard, not a loader.

React Router 8 (data mode)

The auth check hides inside a loader that returns a redirect, so the settings route needs a loader just to guard it.

import { createBrowserRouter, redirect, useLoaderData, type LoaderFunctionArgs } from 'react-router'

const loader = ({ params }: LoaderFunctionArgs) => fetchUser(params.id!)

const router = createBrowserRouter([
  {
    path: '/user/:id',
    loader,
    Component: User,
  },
  {
    path: '/settings',
    loader: () => (isSignedIn() ? null : redirect('/login')),
    Component: Settings,
  },
])

function User() {
  const user = useLoaderData<typeof loader>()
  return <h1>{user.name}</h1>
}
Pyreon

Guards return true, false or a path. The loader types the component.

import { signal } from '@pyreon/reactivity'
import { createRouter, useLoaderData, type LoaderData } from '@pyreon/router'

const signedIn = signal(false)
const loader = ({ params }: { params: Record<string, string> }) => fetchUser(params.id!)

const router = createRouter({
  mode: 'history',
  routes: [
    { path: '/user/:id', component: User, loader },
    { path: '/settings', component: Settings, beforeEnter: () => signedIn() || '/login' },
  ],
})

function User() {
  const user = useLoaderData<LoaderData<typeof loader>>()
  return <h1>{user().name}</h1>
}
coming from

Coming from React Router?

Unsaved-changes protection

React Router
import { useState } from 'react'
import { useBlocker } from 'react-router'

function Editor() {
  const [dirty, setDirty] = useState(false)
  const blocker = useBlocker(() => dirty)
  return (
    <>
      <textarea onChange={() => setDirty(true)} />
      {blocker.state === 'blocked' && (
        <div>
          <p>Leave without saving?</p>
          <button onClick={() => blocker.proceed()}>Leave</button>
          <button onClick={() => blocker.reset()}>Stay</button>
        </div>
      )}
    </>
  )
}
Pyreon

A Pyreon blocker is a predicate: return true to block. It may return a promise, so a custom dialog works too. It covers Back and Forward too, and is removed when the component unmounts.

import { signal } from '@pyreon/reactivity'
import { useBlocker } from '@pyreon/router'

function Editor() {
  const dirty = signal(false)
  useBlocker(() => dirty() && !window.confirm('Leave without saving?'))
  return <textarea onInput={() => dirty.set(true)} />
}

Page number in the URL

React Router
import { useSearchParams } from 'react-router'

function Results() {
  const [params, setParams] = useSearchParams()
  const page = Number(params.get('page') ?? 1)
  return (
    <button
      onClick={() =>
        setParams((prev) => {
          prev.set('page', String(page + 1))
          return prev
        })
      }
    >
      Page {page}
    </button>
  )
}
Pyreon

Values arrive coerced to the declared type, and setSearch merges into the declared params (it replaces the history entry; query keys outside the schema are dropped). For richer rules, give the route a validateSearch function (or a Zod .parse) and read it with useValidatedSearch().

import { useTypedSearchParams } from '@pyreon/router'

function Results() {
  const [search, setSearch] = useTypedSearchParams({ page: 'number' })
  const page = () => search().page || 1 // a missing ?page reads as 0
  return (
    <button onClick={() => setSearch({ page: page() + 1 })}>
      Page {page()}
    </button>
  )
}
try it

Navigate a small app.

Links, typed params, a loader and a guard. The settings page requires sign-in.

app.example.com/

Home

Pick a user or open settings.

navigation log
  1. Click a link.

The route table, the matcher (resolveRoute) and the guard and loader are @pyreon/router's. The history is kept in memory here, because this page's address bar belongs to the site's own router.

benchmarks

Matching at radix-tree speed, hundreds of times ahead of React Router.

At 50 and 200 routes the average ties radix3, the fastest standalone matcher. Framework routers trail by 2.8× to more than 3,000×. Hono wins small tables, and radix3 or find-my-way win most single-shape rows; both stay in the table.

vs radix3, find-my-way, Hono, Next.js path-to-regexp, TanStack Router, Vue Router, React RouterPyreonrival · lower is better
  • 50 routes, average
    tiebest average (1.00×), radix3 1.01×; no CI on this row
  • 200 routes, average
    tie1.03× of radix3; no CI on this row
  • miss → catch-all
    26 ns
    57 ns
    win2.2–2.3× vs find-my-way (57–59 ns) at 50 and 200 routes
  • vs Next.js path-to-regexp
    measured2.8–10.6× faster on average; no CI, no verdict
  • vs TanStack Router
    measured7.7–8.3× faster on average; no CI, no verdict
  • vs Vue Router
    measured7.7–19.0× faster on average; no CI, no verdict
  • vs React Router
    measured885–3,763× faster on average; no CI, no verdict
  • single-shape rows (static, dynamic, splat), 50–200 routes
    lossradix3 or find-my-way 1.2–2.1× ahead per row
  • 10 routes, average
    lossHono 1.91× ahead (its arm skipped building params then; expected to narrow)
Apple M3 Max · record of 2026-11-05 · final pass, one run (Hono's timed arm changed afterwards, PR #4142) · author-run, syntheticFull method, every loss →
what's included

Everything an app router needs, nothing it should guess.

  • createRouter in hash (the default) or history mode, with a url option for server rendering
  • Nested, named and aliased routes, with (.*) catch-alls and lazy() components in a bounded cache
  • Loaders in parallel, with abort on supersede, stale-while-revalidate and a loader cache
  • Guards and middleware: beforeEnter, beforeLeave, global beforeEach/afterEach, and middleware data via useMiddlewareData()
  • useBlocker for unsaved changes, on every in-app navigation and on Back
  • Typed search params: useTypedSearchParams coerces, validateSearch + useValidatedSearch validate
  • Prefetch on intent, hover or viewport, per <RouterLink>
  • View Transitions and route announcements announcements on by default; transitions opt-in, reduced motion respected
  • Tab stacks:next release one back stack per tab for tab-bar apps
  • Native routes on iOS and Android (experimental) with nested routes, beforeEnter, loaders and inbound deep links
recipes

Things to build with it.

A signed-in area that holds on Back

The guard reads a signal. Signed out, /settings redirects to /login, and pressing Back into it after signing out redirects again.

import { signal } from '@pyreon/reactivity'
import { createRouter } from '@pyreon/router'

export const signedIn = signal(false)

const Home = () => <h1>Home</h1>
const Login = () => <h1>Sign in</h1>
const Settings = () => <h1>Settings</h1>

export const router = createRouter({
  mode: 'history',
  routes: [
    { path: '/', component: Home },
    { path: '/login', component: Login },
    { path: '/settings', component: Settings, beforeEnter: () => signedIn() || '/login' },
  ],
})

await router.push('/settings') // 'committed', and you are on /login
signedIn.set(true)
await router.push('/settings') // 'committed', on /settings
await router.push('/')
signedIn.set(false)
history.back()                 // the guard runs again: back on /login
Know when a navigation was refused

A blocker turns a push into 'cancelled', so a save-then-leave flow can tell the user instead of assuming it worked. Mount it only while there are unsaved edits: while a blocker is mounted, closing the tab asks first too.

import { Show } from '@pyreon/core'
import { signal } from '@pyreon/reactivity'
import { useBlocker, useRouter } from '@pyreon/router'

// Mounted only while there are unsaved edits: a mounted blocker also makes
// closing the tab ask first.
const Unsaved = () => {
  useBlocker(() => true)
  return null
}

function Editor() {
  const dirty = signal(false)
  const router = useRouter()

  const leave = async () => {
    const result = await router.push('/')
    if (result === 'cancelled') alert('Save or discard your changes first.')
  }

  return (
    <div>
      <Show when={dirty()}>
        <Unsaved />
      </Show>
      <textarea onInput={() => dirty.set(true)} />
      <button onClick={leave}>Done</button>
    </div>
  )
}
next release
One back stack per tab

A tab-bar app keeps a separate history per tab: switching tabs returns to where that tab was, and Back walks only the current tab's stack.

import { createRouter } from '@pyreon/router'

const Feed = () => <h1>Feed</h1>
const Search = () => <h1>Search</h1>
const Profile = () => <h1>Profile</h1>
const Post = () => <h1>Post</h1>

export const router = createRouter({
  mode: 'history',
  routes: [
    { path: '/', component: Feed },
    { path: '/post/:id', component: Post },
    { path: '/search', component: Search },
    { path: '/profile', component: Profile },
  ],
  tabs: [
    { name: 'home', root: '/' },
    { name: 'search', root: '/search' },
    { name: 'profile', root: '/profile' },
  ],
})
api

The whole surface.

Every export has a reference page with its signature, an example and the mistakes people make with it.

setup · 5
  • createRouter
  • RouterProvider
  • RouterView
  • RouterLink
  • lazy
hooks · 12
  • useRouter
  • useRoute
  • useParams
  • useNavigate
  • useLoaderData
  • useSearchParams
  • useTypedSearchParams
  • useValidatedSearch
  • useIsActive
  • useBlocker
  • useTransition
  • useMiddlewareData
guards and errors · 5
  • redirect
  • notFound
  • NotFoundBoundary
  • onBeforeRouteLeave
  • onBeforeRouteUpdate
types and utilities · 7
  • LoaderData
  • ExtractParams
  • NavigationResult
  • buildPath
  • resolveRoute
  • parseQuery
  • stringifyQuery
good to know

Good to know before you start.

Guards aren't security

A client-side guard only hides a page. Check access on the server too (with Zero, in route middleware or a .server.ts loader).

Hash mode is the default

Set mode: 'history' for clean URLs, and serve the app for every path.

Loader params are strings

A loader sees params as Record<string, string>. For params typed from the path, read them with useRoute<'/user/:id'>(), or let Zero's typedRoutes check every link.

File-based routes come from Zero

The router takes a route list. Zero builds that list from src/routes on the web; native apps declare it as an array.

questions

What people ask first.

Does route matching speed matter?

Rarely as a bottleneck, which is the point: it stays out of the way at any route count. It is level with radix3, the fastest standalone matcher we measured, at 50 and 200 routes; Hono led at 10 routes, 1.91×, in the published run, measured before a harness fix that adds work to Hono's timed arm (PR #4142).

How are params typed?

ExtractParams<'/user/:id'> is { id: string }, and useRoute<'/user/:id'>()().params.id is typed. createRouter<'home' | 'user'> types named navigation, and Zero's typedRoutes makes a mistyped <RouterLink to> a compile error.

Does it work with server rendering?

Yes. Pass the request URL as url, and loaders run before the HTML is written; their data is serialised so hydration does not fetch again. Zero wires all of it, including server-only loaders in .server.ts files.

Is it the same router on iOS and Android?

The same API: RouterProvider, RouterView, useNavigate, useParams, useLoaderData and beforeEnter, lowered to SwiftUI's NavigationStack and to Compose on the experimental native targets. Inbound deep links route through it, cold and warm.

Can I opt out of the announcements or transitions?

<RouterView announceRouteChanges={false} /> turns off the announcer, and transitions are off unless you turn them on — createRouter({ viewTransition: true }), or meta: { viewTransition: true } for one route (false opts a route out).

Press Back with confidence. Your guards will be there.

bun add @pyreon/router
Read the router guide