Skip to content

@kiln-js/client

@kiln-js/client is the browser runtime. It hydrates server-rendered pages, mounts client-only pages, navigates between pages without a full reload, prefetches loader data on hover, and hydrates islands. It also provides Link and an error boundary.

bash
bun add @kiln-js/client

Most projects use the generated client entry, which calls createClient for you. Write your own entry only when you need to change how the client starts.


Exports at a glance

ExportKindPurpose
createClient(options?)functionBuild a client object with a start() method.
navigate(to, options?)functionNavigate to a same-site URL without a reload.
prefetch(to)functionLoad a route's code and loader data before a click.
invalidate(path?)functionDiscard prefetched loader data.
LinkcomponentAn anchor that navigates within the app.
ErrorBoundarycomponentCatches errors in its children and shows a fallback.
usePathname, useParamshooksRe-exported from @kiln-js/core.
ClientOnly, useIsClientcomponents and hooksRe-exported from @kiln-js/core.
Await, deferfunctionsRe-exported from @kiln-js/core.

Types: LinkProps, ClientRoute, KilnBoot, RenderMode.


createClient(options?)

Returns a promise for an object with a start() method. Calling start() reads the boot data, loads the page's code, and hydrates the page.

tsx
import { createClient } from "@kiln-js/client";

createClient().then((client) => client.start());

Options

ts
interface ClientOptions {
  routes?: ClientRoute[];
}

When routes is not passed, the client reads the __KILN_ROUTES__ global that the Vite plugin injects. If the global is missing, it throws No routes found. Pass routes yourself only when you build the route table by hand.

What start() does

  1. Records the document title, so navigation can restore it.
  2. Turns off the browser's own scroll restoration and listens for popstate.
  3. Reads window.__KILN__, the boot data the server wrote into the page.
  4. If the page has islands, it hydrates each island on its own and stops there. The page itself is not hydrated.
  5. Otherwise it loads the page module and its layouts, then:
    • For client pages, it mounts the tree with createRoot, which renders without server HTML.
    • For universal pages, it hydrates the existing HTML with hydrateRoot.

If the page mode is server and has no islands, the server sends no boot data, and no client script runs.

Hydration mismatches

Hydration mismatches are reported through a viewer that shows the server HTML next to what the browser rendered. Use ClientOnly or useIsClient to avoid mismatches on values that differ between server and browser, such as dates and random numbers.


Navigates to a URL. Same-site URLs are handled inside the app. Other URLs cause a full page load.

ts
import { navigate } from "@kiln-js/client";

await navigate("/dashboard");
await navigate("/dashboard", { push: false });       // replace the history entry
await navigate("/docs#install", { scroll: false });  // keep the scroll position

Options

OptionDefaultMeaning
pushtrueAdd a history entry. When false, the current entry is replaced.
scrolltrueScroll to the top after navigating. Ignored when restoreY is set.
restoreYnoneScroll to this vertical offset. Used for back and forward.

Passing a boolean is accepted for compatibility and means push.

Behavior

  • If the target is not a same-origin URL, the browser goes there with location.href.
  • If the target page is server mode, which has no client code, the browser loads it normally.
  • If the page is not mounted yet, for example on a server-only page with islands, the browser loads it normally.
  • Loader data comes from the prefetch cache when it exists. Otherwise it is fetched from /__kiln/data.
  • A loader redirect is followed with location.assign.
  • If a newer navigation starts while this one is loading, this one is dropped. The last click wins.
  • If anything fails, the client logs the error and loads the page normally.
  • After a navigation with a #hash, the element with that id is scrolled into view.

prefetch(to)

Loads the target route's code and, for non-client pages, starts fetching its loader data. The data is kept until a navigation uses it. Link calls prefetch on mouse enter and on focus.

ts
import { prefetch } from "@kiln-js/client";

prefetch("/blog/hello");

Prefetching does nothing for cross-origin URLs or routes that cannot be navigated to.

invalidate(path?)

Discards prefetched loader data. Call it after a change makes the cached data stale.

ts
import { invalidate } from "@kiln-js/client";

invalidate("/blog/hello"); // one path
invalidate();              // everything

Loader data is fetched fresh on the next navigation after invalidation.


An anchor that navigates within the app, and falls back to the browser for anything else.

tsx
import { Link } from "@kiln-js/client";

<Link href="/about" className="nav-link">About</Link>

LinkProps extends AnchorHTMLAttributes<HTMLAnchorElement> and requires href. Any other anchor attribute passes through.

When a click should use the browser's default instead of the app router, Link leaves it alone. That happens for:

  • Ctrl, Cmd, Shift, Alt, or a middle-button click
  • target set to anything other than _self
  • the download attribute
  • a cross-origin href
  • a hash link to the current page, such as #section while already on that page

The other cases are navigated with navigate, and the default click is prevented.

Hovering or focusing a Link calls prefetch for its href. Your own onClick, onMouseEnter, and onFocus handlers still run first.


ErrorBoundary

A React error boundary. Kiln wraps the whole app in one, and wraps each page in another keyed by the pathname. A crash in a page shows the nearest boundary's fallback and leaves the layouts working, so navigation still works. Use it yourself when you want a fallback for part of a page:

tsx
import { ErrorBoundary } from "@kiln-js/client";

<ErrorBoundary>
  <Chart />
</ErrorBoundary>

Error boundaries catch errors during rendering and lifecycle methods. They do not catch errors in event handlers or in async code. Handle those yourself.


Re-exports from @kiln-js/core

  • usePathname(): the current pathname.
  • useParams(): the current route params.
  • ClientOnly and useIsClient(): render only in the browser.
  • Await and defer: streamed data.

Types

ts
export type RenderMode = "universal" | "server" | "client";

export interface ClientRoute {
  pattern: string;
  mode: RenderMode;
  load: (() => Promise<{ default: ComponentType<any>; loader?: unknown }>) | null;
  layouts: (() => Promise<{ default: ComponentType<any> }>)[];
}

export interface KilnBoot {
  mode: RenderMode;
  pattern: string;
  data: unknown;
  islands?: boolean;
}

export interface LinkProps extends AnchorHTMLAttributes<HTMLAnchorElement> {
  href: string;
}

KilnBoot is the object the server writes to window.__KILN__. Its islands flag tells the client whether the page contains islands.