Docs

Routing

Routes are files under routes/. The file path is the URL - no route config to maintain.

Conventions

  • index.tsx → the parent path; about.tsx → /about.
  • [id].tsx → a dynamic segment :id (read via c.params.id / the loader).
  • [...path].tsx → a catch-all capturing the rest of the URL into one param (params.path = "a/b/c"). Must be the last segment; matches one or more segments (so /files won't match /files/[...path]).
  • [[lang]].tsx → an optional segment: it matches both with and without the segment. [[lang]]/about.tsx serves /about (params.lang === undefined) and /:lang/about - handy for an optional locale prefix. It expands to one route per combination, all sharing the page + layout chain (so n optionals → 2ⁿ patterns).
  • (group)/ → a route group: the folder organizes routes (and can hold its own _layout.tsx) without adding a URL segment - e.g. (marketing)/pricing.tsx → /pricing.
  • _layout.tsx wraps its directory; nesting them builds a layout chain (this docs sidebar is a nested layout).
  • x.backend.ts beside a page or layout is its server half: loader, action, their output schemas, and the other server-only exports. It never reaches the browser - see Project structure.
  • _404.tsx renders unmatched paths, and whatever a loader answers with notFound(). At the routes root it renders inside the root layout, as below. In a directory below (admin/_404.tsx) it answers for that part of the app: the unmatched URLs under /admin and notFound() from the routes beneath it, the nearest one winning, rendered inside the layouts at or above it with their loader data. Those layouts run as they do for a page, so a gate decides first - its redirect is the answer, and its own notFound() shows the root page rather than the area's. A nested _404 is served non-hydrated and never from a shared cache once a layout loaded data for it; a navigation that lands on one loads the URL as a document. Two route groups with a _404 at one URL prefix are a boot error unless a directory containing both has one too. gone(), statusPage() and the _410.tsx-style pages stay at the root, as does the 404 of a static export. A helper the browser also loads imports these three from @nifrajs/web/client rather than the root, whose server half Vite's dev server would otherwise send it.
  • A root status page (_404.tsx, _503.tsx, ...) or an _error.tsx renders inside the layouts above it with their loader data, and the server puts its meta in the head. For a request no route ran (an unmatched URL) the root middleware and layout loaders run first; otherwise the page reuses the data the request already loaded. When those layouts cannot render it - a loader throws, a gate or the middleware refuses - a root status page renders alone and an _error inside its layouts without their data, with the same status, so a status page never fails into a second error. The response is private, no-store once a layout loaded data, and a navigation that lands on one loads the URL as a document. export const inLayouts = false always renders the page that way and runs no layout loader for it. A root status page that wraps the root layout itself would render it twice; nifra check reports one as NF-C034.
  • _loading.tsx is what the page slot shows while a client navigation loads. A navigation still waiting on its data after about 120 ms swaps the page for the target route's nearest _loading: the innermost one above it whose layouts are already on screen. Those are the layouts the two pages share, and they stay mounted with their data. A _loading never renders outside a layout above it - coming from outside /admin, admin/_loading.tsx waits for the admin layout and the root one shows instead. A navigation that settles sooner (a prefetched link, a fast loader) goes straight to the new page, as does one with no eligible _loading; a change of search on the same path and a form submit keep the page and report pending. The component receives pending and no data. React's NavLink widens this to a per-link signal: its className, style and children take functions over { isActive, isPending }, where isPending is true while a navigation into that link's own target is in flight; the other adapters expose the route-level pending described here only. It is a browser-only convention on every adapter - the first load of a URL is a server render, where defer() streams the slow part.
  • _error.tsx is the segment's error boundary. On the server - if a route's loader or shell render throws - the nearest _error (in the route's ancestor chain) renders in its place, wrapped by the layouts at/above that segment, at status 500 (served non-hydrated). On the client - a render error during navigation/interaction is caught by the nearest boundary, which renders _error in place (all five adapters). It receives the serialized error as { data: { name, message } } (never the stack; on the server, a generic Internal Server Error rather than the error's own text unless NODE_ENV is development or test); a thrown control-flow value (e.g. a guard redirect) passes through.
  • A _layout.backend.ts that exports middleware runs it on the server before the layouts, loaders and actions of every route in its directory and below, with or without a _layout.tsx beside it - see Route middleware.
TS
routes/
  _layout.tsx        wraps every page (chain: outer → inner)
  _layout.backend.ts its loader, and middleware for every page below it
  _error.tsx         error boundary (a loader throws → renders here, 500)
  _loading.tsx       the page slot while a client navigation loads
  index.tsx          →  /
  index.backend.ts       its loader + action - never reaches the browser
  about.tsx          →  /about
  users/
    [id].tsx         →  /users/:id          dynamic segment
    [id].backend.ts
  files/
    [...path].tsx    →  /files/*path         catch-all (the rest of the path)
  [[lang]]/          optional segment - matches WITH and WITHOUT it
    docs.tsx         →  /docs  AND  /:lang/docs
  (marketing)/       route group: organizes + can hold its own _layout,
    _layout.tsx        but contributes NO URL segment
    pricing.tsx      →  /pricing

A route

Each page default-exports a component; an optional meta export drives <head> (applied on SSR and on client navigation). Its data comes from a loader in its .backend.ts half - see Loaders & actions.

A layout's meta receives its own loader's data as data, the value its component renders, or null when the layout has no loader. The page's data is pageData, for a layout title template. A layout that loads the locale can set lang from its data, and a client navigation keeps it. nifra check reports a layout with no loader whose meta reads data as NF-C040.

TS
// routes/users/[id].tsx
import type { Route } from "./+types/[id]"

export const meta = { title: "User" }   // injected into <head> (SSR + client nav)

export default function User({ data }: Route.ComponentProps) {
  return <h1>User {data.name}</h1>
}
TS
// routes/users/[id].backend.ts - its server half
import { t } from "@nifrajs/schema"
import type { Route } from "./+types/[id]"

export const loaderOutput = t.object({ name: t.string() })

export async function loader({ params }: Route.LoaderArgs) {
  return { name: `User ${params.id}` }
}

Route middleware

A directory's _layout.backend.ts exports middleware, a function that runs on the server before everything under its directory: the layouts' loaders, gates included, then the page's loader or action. It runs for a document request, a client navigation and a form post alike, and before a nested _404 there. Middleware higher in the tree runs first.

TS
// routes/account/_layout.backend.ts - runs before every page under /account
import { type RouteMiddleware, rawHref, redirect } from "@nifrajs/web"

export const middleware: RouteMiddleware = ({ request, set }) => {
  set.headers["cache-control"] = "private, no-store"
  const signedIn = request.headers.get("cookie")?.includes("session=") ?? false
  return signedIn ? undefined : redirect(rawHref("/login"))
}
  • Return nothing to let the request through. Return or throw a redirect(), a status such as notFound(), or a Response to answer with it, and nothing below it runs. During a client navigation, the router follows a redirect to another page of the app without reloading, and the address bar shows the target.
  • set adds headers and cookies like a loader's; a layout's or the page's header of the same name wins. params holds the params of the directory's URL prefix.
  • It covers pages only: a prerendered page, an ISR cache hit, a mounted API and a static file are served without it. For middleware on every request, export use from backend/framework.ts: export const use = (app) => app.use(securityHeaders()).

Catch-all routes

A [...name].tsx segment matches the rest of the path and hands it to the loader in [...name].backend.ts as a single string param - ideal for docs/CMS trees, file browsers, or a custom fallback. It must be the final segment.

TS
// routes/files/[...path].backend.ts - the page is routes/files/[...path].tsx, and together they
// match /files/a, /files/a/b/c.txt, …
import { t } from "@nifrajs/schema"

declare function read(path: string): Promise<string>

export const loaderOutput = t.object({ file: t.string() })

export async function loader({ params }: { params: { path: string } }) {
  const path = params.path          // "a/b/c.txt" - the matched tail, as one string
  return { file: await read(path) }
}
// A catch-all needs ≥1 segment (/files alone won't match) and must be the last segment.

Client-only pages

export const ssr = false keeps a page's component off the server. The route is still matched, its layouts still render, its gates and its loader still run and the data is still embedded - only the component is skipped. The server puts the page's HydrateFallback in the page slot (nothing, if there is none), the browser hydrates that, then renders the component with the data it already has. A client navigation to the page renders the component directly. For a component that reads window, a canvas, or a browser-only library while it renders.

TSX
// routes/map.tsx - a page whose component needs a browser to render.
import type { Route } from "./+types/map"

export const ssr = false

// What the server puts in the page slot, and what the browser shows until the component renders.
// Same props as the component - the loader data is already there.
export function HydrateFallback({ data }: Route.ComponentProps) {
  return <p>Loading {data.pins.length} pins…</p>
}

export default function MapPage({ data }: Route.ComponentProps) {
  const width = window.innerWidth         // fine: this never runs on the server
  return <Canvas width={width} pins={data.pins} />
}

// routes/map.backend.ts - the loader still runs on the server, and its data is embedded.
export const loaderOutput = t.object({ pins: t.array(Pin) })
export async function loader({ api }: Route.LoaderArgs) {
  const res = await api.pins.get()
  return { pins: res.ok ? res.data : [] }
}

The page module is still imported on the server, for its options (its loader lives in the .backend.ts half). An import that needs a browser at load time therefore belongs inside the component - a dynamic import() - not at the top of the file. ssr = false cannot be combined with hydrate = false: nothing would ever render the page.

Typed search params

Export a searchSchema - any Standard Schema (valibot, zod, arktype) - and the URL query becomes typed and validated on both sides: the loader receives it as ctx.search and the component reads the same value with useSearch<typeof searchSchema>(). Invalid or hostile input fails closed to the schema's defaults (never a 500), and the value is derived identically on the server and on each client navigation - so a query-reading page hydrates with no mismatch and never touches window.location.search by hand.

TSX
// routes/reports.tsx - a typed, validated ?page=&sort= query.
import { useSearch } from "@nifrajs/web-react/router"
import * as v from "valibot" // any Standard Schema works (valibot, zod, arktype)
import type { Route } from "./+types/reports"

// The route's search contract. Invalid or hostile input fails closed to these defaults - never a 500.
export const searchSchema = v.object({
  page: v.optional(v.fallback(v.number(), 1), 1),
  sort: v.optional(v.picklist(["new", "top"]), "new"),
})

// The component reads the SAME value - SSR-correct, so page/sort hydrate with no mismatch and you
// never parse window.location.search by hand.
export default function Reports({ data }: Route.ComponentProps) {
  const { page, sort } = useSearch<typeof searchSchema>() // { page: number; sort: "new" | "top" }
  return <Pager page={page} sort={sort} rows={data.rows} />
}

// routes/reports.backend.ts - the loader receives the validated query as `search`, typed from
// the page's searchSchema by the generated Route.LoaderArgs.
export const loaderOutput = t.object({ rows: t.array(Report) })
export async function loader({ search, api }: Route.LoaderArgs) {
  const res = await api.reports.list(search).get() // search.page is a number
  return { rows: res.ok ? res.data : [] }
}

Without a searchSchema, ctx.search and useSearch() are the raw parsed query (Record<string, unknown>). useSearch ships on every adapter (React, Preact, Vue, Solid, Svelte), each in that framework's shape - a value on React/Preact, a Ref on Vue, an accessor on Solid/Svelte. For imperative reads and writes of the raw query, useSearchParams() mirrors react-router's [params, setParams] tuple.

To WRITE search, build the link with href and hand it to useNavigate: navigate(href({ to: "/reports", search: { page: 2 } })). href and rawHref are exported by every adapter's router entry (@nifrajs/web-<framework>/router). nifra dev, nifra build, nifra check and nifra types write .nifra/types/routes.d.ts, which maps every route pattern to its params and its schema output, and each route's generated ./+types module loads it. So to is one of those patterns, params holds that route's params, and search is typed against its schema: a misspelt route, a missing param and a wrong search shape are compile errors, and a changed searchSchema shows up as a tsc error at the stale call. A route without a searchSchema takes any search.

Each param is encoded as one path segment, so a value such as a/b or //evil.com stays inside the segment and never changes where the link goes. A param that is missing, empty, ., .. or an unpaired surrogate throws a TypeError naming it. navigate takes only an href result, or a history delta such as navigate(-1); a string or a template literal is a compile error. So do React's Link, NavLink and Navigate (<Link to={href({ to: "/pricing" })}>) and the server's redirect(); when to is not a same-origin path, Link and NavLink render the anchor without an href, and Navigate and setSearchParams do not navigate; each logs a console.error that names the call and never the value. redirect takes an off-origin location with { external: true }, which still refuses one holding a line break. For a same-origin path built elsewhere - a CMS link, /llms.txt - rawHref("/llms.txt") checks it (one leading /, no backslash or control character) and returns the same type. A link to another site is a plain <a href>. A path that comes from outside is checked where it is read: rawHref throws a TypeError for one that is not same-origin, so catch it at that call when a field cannot be trusted. A value that gets past it as a forged Href costs only its own link.

A link written as a string is not checked: navigate("/pricng") and <a href="/pricng"> compile and then 404. Moving one is mechanical.

TSX
// doc-check: skip - routes of your own app; one line per call, before and after.
import { href, rawHref } from "@nifrajs/web-react/router"

navigate(`/users/${id}?tab=posts`)
navigate(href({ to: "/users/:id", params: { id }, search: { tab: "posts" } }))

<a href="/pricing">Pricing</a>
<a href={href({ to: "/pricing" })}>Pricing</a>

<Link to="/docs#install">Install</Link>
<Link to={href({ to: "/docs", hash: "install" })}>Install</Link>

throw redirect("/login")
throw redirect(href({ to: "/login" }))

navigate(cmsLink) // a same-origin path built elsewhere
navigate(rawHref(cmsLink))

A leftover navigate("/x"), <Link to="/x"> or redirect("/x") is a compile error at the call, so tsc lists what is left. A plain <a href="/x"> is not an error, so search for href="/ and href={`/ too; a link that opens another site stays an <a href>. This site, the examples and the starters are held to it by a test that fails on a literal internal anchor.

nifra check finds the plain anchors in your app too, and reads the route table to tell two cases apart. NF-C057 (a warning) is a path that no page, no backend route and no file in public/ serves: the link is a 404, and the message names the nearest page when it is a typo away. NF-C058 (info) is a path that is a page today; the message gives the href() call that replaces it. A template literal such as `/users/${id}` is judged by its shape and never reported as dead, since the route it builds may live outside the file routes. Links in .tsx, .vue and .svelte files are read. Raise, lower or silence either code with rules in nifra.config, or keep one link as written with rawHref() or // nifra-expect NF-C058: <reason> above the attribute (<!-- nifra-expect NF-C058: <reason> --> above the anchor in a .vue or .svelte template). A backend mounted under apiPrefix counts as serving its paths, read from backend/framework.ts or nifra.config.ts; when either holds a value check cannot read, no link is reported dead. .jsx files and an href built by a function are not read.

The table is a generated file, .nifra/types/routes.d.ts. A program in which no route imports a ./+types/... module does not load it, and to then accepts no route at all, and nifra check warns. List .nifra/types/routes.d.ts under the tsconfig files: the ** globs skip a dot directory, and a files entry is not filtered by exclude.

Prefetching

A link warms its route - the route's code and its loader data - before it is followed, so the click renders at once. data-nifra-prefetch, on the link or on any element around it (the nearest one wins), says when:

  • intent (the default): on hover or keyboard focus.
  • viewport: once the link scrolls into view.
  • render: as soon as a page shows the link.
  • none: never; the route loads when the link is followed.
TSX
// A docs sidebar: each link loads as it scrolls into view.
<nav data-nifra-prefetch="viewport">
  <a href="/docs/routing">Routing</a>
  <a href="/docs/data">Data</a>
  {/* The nearest attribute wins: this one waits for the click. */}
  <a href="/reports/annual" data-nifra-prefetch="none">Annual report</a>
</nav>

// React's <Link> takes it as a prop.
<Link to={href({ to: "/pricing" })} prefetch="render">Pricing</Link>

Warmed data is used by a click within 30 seconds; after that the click loads the route again, so a link that scrolled into view long ago never shows old data. The page already on screen is never prefetched. viewport and render links are found when the page loads and whenever the router settles (a navigation, a submit); a link the page adds in between warms on intent until then. Both run the target's loaders before anyone clicks, so keep them to links people are likely to follow. The attribute works the same under every adapter; React's <Link> and <NavLink> also take it as a prefetch prop.

Breadcrumbs and the rendered chain

A page or a layout can export a handle - any value; nifra only passes it along. useMatches() returns the chain being rendered, outermost layout first and the page last, each entry as { id, pathname, params, data, handle }: id is the route file without its extension, pathname the part of the URL it covers (a layout its directory's prefix, the page the whole path, never the query), params the ones it declares, and data its loader data (null without a loader). A layout can therefore build breadcrumbs, a title, or a section nav from what the routes below it export.

TSX
// routes/orgs/[org]/_layout.tsx
import type { ReactNode } from "react"
import { useMatches } from "@nifrajs/web-react/router"

export const handle = { crumb: "Organization" }

export default function OrgLayout({ children }: { children: ReactNode }) {
  // Outermost layout first, then the page: { id, pathname, params, data, handle }.
  const crumbs = useMatches().flatMap((m) => {
    const crumb = (m.handle as { crumb?: string } | undefined)?.crumb
    return crumb === undefined ? [] : [{ href: m.pathname, crumb }]
  })
  return (
    <>
      <nav aria-label="Breadcrumb">
        {crumbs.map((c) => <a key={c.href} href={c.href}>{c.crumb}</a>)}
      </nav>
      {children}
    </>
  )
}

The server render and the browser report the same list, so a breadcrumb trail hydrates with no mismatch. handle is read from the module on each side, never serialized, so it can hold a function or a component. While a _loading page is up it takes the page's place in the list; a nested _404 reports the layouts it renders inside; an _error page the server renders reports an empty list. useMatches ships on every adapter from @nifrajs/web-<framework>/router, as an array on React/Preact, a Ref on Vue, and an accessor on Solid/Svelte.

A photo grid can open /photos/7 over the grid, while a shared link or a reload of that URL shows the photo as its own page. A layout or page declares this with a boundary whose mode is { intercept: "/photos/:id" }, in its boundaries export. On a client navigation from a page under that layout (or from that page) to a matching URL, nifra fetches the target route's data with the usual request, so its middleware, gates and loader all run. The current page stays mounted, the address bar shows the new URL, and the target's loader data arrives as boundaries.photo with status: "ready". Until then the boundary's status is "unresolved".

TSX
// routes/_layout.tsx - a link to /photos/:id from any page opens the photo over that page
import type { Boundary, BoundaryStates } from "@nifrajs/web"
// /client, not the root: the root carries the server, which a browser bundle must not load.
import { closeBoundary } from "@nifrajs/web/client"
import type { ReactNode } from "react"
import type { Route as Photo } from "./photos/+types/[id]"

// No load of its own: the modal shows the target page's loader data.
const photo: Boundary<Photo.LoaderData, ReactNode> = {
  name: "photo",
  mode: { intercept: "/photos/:id" },
  render: (data) => <h2>{data.title}</h2>,
}

export const boundaries = [photo]

export default function Layout(props: { children?: ReactNode; boundaries?: BoundaryStates }) {
  const open = props.boundaries?.photo
  return (
    <>
      {props.children}
      {open?.status === "ready" || open?.status === "error" ? (
        // A form in here with no action posts to the photo's route, not the page's.
        <dialog open data-nifra-boundary="photo">
          {open.status === "ready" ? photo.render(open.data as Photo.LoaderData) : <p>Could not load.</p>}
          <button type="button" onClick={() => closeBoundary("photo")}>
            Close
          </button>
        </dialog>
      ) : null}
    </>
  )
}
  • The boundary has no load: its data is the target page's loader data, so type it with that route's LoaderData. routes/photos/[id].tsx stays an ordinary page.
  • Back closes the modal and forward reopens it. Closing shows the page underneath as it was, with its loader data and boundaries, without fetching it again; a page loaded for a previous visitor loads again. A link inside the modal to another matching URL replaces its content, and back steps through each one. Navigating anywhere else closes it.
  • A reload, a shared link, or a navigation from a page outside the declaring layout or page renders the target as a full page. That includes coming back to the modal's URL from a page that does not intercept it.
  • A target that answers with its own status, such as a 404 or 401, or that throws, never opens in the modal: the browser loads that URL as a full page and gets that answer. A redirect is followed first, and opens in the modal only when it lands on another matching URL.
  • closeBoundary("photo") from @nifrajs/web/client closes it: it goes back through the entries the modal added, or replaces the modal's URL with the page's when those entries are not in this tab's history (the modal was opened with a replace navigation). It does nothing when that boundary holds no target.
  • While the modal is open, the route props and hooks describe the page underneath: useLocation, useSearch, useParams and useMatches report the page's path, query and params, while the address bar shows the modal's URL.
  • Opening the modal keeps the page's scroll position and its actionData, and closing it restores the page's entry with its scroll. A link to the page's own URL is a normal navigation, never an interception, and only one intercept boundary is open at a time: opening another closes the first.
  • An action submitted while the modal is open revalidates both routes: the page reloads under its own URL and the target under the modal's, each with its own cache entry. With revalidate: false, only the paths the server names as changed reload. invalidate() reloads both, and invalidate(paths) reloads the ones listed. If the target answers a reload with a status or throws, the modal stays open and the boundary's status becomes "error" with a generic error, so none of that answer reaches the page.
  • A form with no action (or a submitter with no formaction), POST or GET, submits to the route that owns it: the target's URL when the form sits inside an element with data-nifra-boundary="photo", otherwise the page's URL. A form with an explicit action posts where it says. The result of an action posted to the target arrives as boundaries.photo.actionData, and the page's own actionData stays the page's. An action that redirects renders the redirect's target as a full page, never in the modal.
  • The component renders the boundary itself: it reads boundaries.<name> from its props and calls the boundary's render with the data. Every adapter passes boundaries to the layouts and the page.

Independently navigable route slots

An intercepted route is useful for one modal over its owning page. A dashboard with several panels that open, change route, and close independently uses route slots. The page declares named slots and an allowlist of route patterns for each. A slot renders that target's full layout and page chain in its own component tree; each slot has separate loading and error UI.

TSX
// routes/dashboard.tsx - name the only route identities this panel may display
import { href } from "@nifrajs/web"
import { RouteSlot, useRouteSlot } from "@nifrajs/web-react/router"

export const routeSlots = {
  inspector: ["/users/:id"],
  activity: ["/activity"],
} as const

export default function Dashboard() {
  const inspector = useRouteSlot("inspector")
  return (
    <>
      <button type="button" onClick={() => inspector.open(href({ to: "/users/:id", params: { id: "7" } }))}>
        Inspect user 7
      </button>
      <RouteSlot name="inspector" fallback={<p>Select a user.</p>} />
      <RouteSlot name="activity" fallback={<p>Activity is closed.</p>} />
    </>
  )
}

// A shareable link can open more than one panel at once.
const dashboard = href({
  to: "/dashboard",
  slots: {
    inspector: href({ to: "/users/:id", params: { id: "7" } }),
    activity: href({ to: "/activity" }),
  },
})
  • Generated route types constrain the slot name and target route passed to href. At runtime, the client checks slot-only navigation against the page's registration and route identity, and the server applies the same checks to direct requests. Malformed, duplicate, unknown, or oversized slot state is rejected before rendering; the server returns 400 for an invalid direct URL. The reserved flat query keys use the form slot.<name>=<target>, allow at most four targets, 1,024 encoded characters per target, and 4,096 encoded characters total. They are removed before application search parsing, while unrelated query text stays intact.
  • The server sends only the page shell. After hydration, each target loads through the normal same-origin route-data request, so its middleware, gates, and loader run with the current request's authorization. Target data is never embedded in the cached shell. Slot URLs are inputs, never authorization grants; keep sensitive values out because URLs can appear in Referer headers, logs, and analytics. Identity changes clear old data before reauthorization. Returning focus revalidates at most once per 30 seconds while keeping ready content visible, and navigation cancels stale work.
  • Opening, changing, and closing a slot create history entries; Browser Back and Forward restore the previous slot URLs. Updating one slot retains sibling slots and the page's own loader data; changing slot state alone does not rerun that page loader. Up to four slot targets may be open at once, with bounded concurrent loading.
  • Slot content is client-rendered in this first slice: server HTML contains the fallback, then hydration performs an authorized route-data fetch. This works well for overlays and modals; always-visible panels incur that post-hydration request.
  • React, Preact, Solid, and Vue export RouteSlot and useRouteSlot from their /router entry. Svelte exports useRouteSlot from @nifrajs/web-svelte/router and the RouteSlot component from @nifrajs/web-svelte/route-slot.

Guarding navigation

A page with unsaved work shouldn't lose it to a stray click or the back button. useBlocker (from @nifrajs/web-react/router) intercepts a navigation - a <Link>/anchor click, useNavigate, or a browser back/forward - and hands you { state, proceed, reset }. Pass a boolean or a ({ currentLocation, nextLocation }) => boolean predicate; when a navigation is held, state becomes "blocked", so you render your OWN confirmation and call proceed() to continue or reset() to stay. It mirrors react-router's shape - a plain boolean can't express an async "are you sure?", these two callbacks can.

TSX
// routes/posts/[id]/edit.tsx - don't lose a half-finished edit to a stray click.
import { useState } from "react"
import { useBlocker } from "@nifrajs/web-react/router"

export default function EditPost() {
  const [dirty, setDirty] = useState(false)
  // A boolean, or a predicate of { currentLocation, nextLocation } for finer control
  // (e.g. allow moves within the editor, block only real exits).
  const blocker = useBlocker(dirty)

  return (
    <form onInput={() => setDirty(true)} onSubmit={() => setDirty(false)}>
      {/* ...fields... */}
      {blocker.state === "blocked" && (
        <div role="dialog" aria-modal="true">
          <p>You have unsaved changes.</p>
          <button type="button" onClick={blocker.reset}>Keep editing</button>
          <button type="button" onClick={blocker.proceed}>Discard</button>
        </div>
      )}
    </form>
  )
}

It also arms the browser's native "Leave site?" prompt on tab close / reload (the browser shows its own text there - a custom message isn't possible). On the server and before hydration the blocker is idle (it never blocks), so navigation degrades to the native <a> and the page is hydration-safe.

useNavigate and useBlocker ship on every adapter - @nifrajs/web-<framework>/router on Preact, Vue, Solid and Svelte too, each returning the blocker in that framework's own shape (a Vue ref, a Solid accessor, a Svelte store, a plain value in Preact/React). In Vue, Solid and Svelte the hook is created once, so pass a function - useBlocker(() => dirty) - to track a changing flag.