Navigate API

primate/navigate exports browser navigation operations and their public TypeScript types.

import navigate from "primate/navigate";
import type {
  NavigateOptions,
  NavigationRefreshOptions,
  NavigationEventDetail,
  NavigationListener,
  NavigationSource,
} from "primate/navigate";

The runtime API is client-only. Import it from hydrated frontend or other browser code, not server rendering code. See the Client navigation guide for links, forms, partitions, and workflow examples.

function navigate(
  href: string,
  optionsOrEvent?: NavigateOptions | Event,
  event?: Event,
): Promise<void>;

Resolves href against the current page. Same-origin pathname or query changes fetch and apply a Primate page response, update history, and scroll to the destination hash. Cross-origin and non-page responses use location.assign() for normal document navigation.

The optional event may be passed as the second argument, or as the third when using options. Same-origin navigation calls preventDefault(); cross-origin navigation leaves a supplied event untouched. The promise resolves after the SPA operation completes, is superseded/fails, performs a shallow/hash update, or hands navigation to the browser. It does not return a success flag.

await navigate("/projects/42", { replace: true });

Options accepted by navigate().

type NavigateOptions = {
  replace?: boolean;
  shallow?: boolean;
  state?: unknown;
};

All members default to their absent/false behavior.

options.replace

replace?: boolean;

When true, replaces the current history entry instead of pushing a new one. It applies to full SPA, hash-only, and shallow same-origin navigation.

options.shallow

shallow?: boolean;

When true and the destination pathname matches the current pathname, updates the URL, entry state, and public request data without fetching, remounting, or scrolling. A different pathname performs normal navigation.

options.state

state?: unknown;

Ephemeral state associated with the destination history entry. Primate clones it with structuredClone; an unclonable value rejects navigate() before the current entry changes. State is retained only within the same client partition and document and is not exposed in public history.state.

refresh(options?: NavigationRefreshOptions): Promise<boolean>;

Fetches and applies fresh page data for the current pathname and query without changing URL/history or scrolling. Resolves true only when a successful Primate route response is applied and completion listeners run. It resolves false for failure, supersession, redirects/different requested locations, or non-page responses.

Foreground navigation supersedes a running refresh and schedules a replacement with the interrupted attempt's header snapshot; its original promise resolves false. The replacement runs before other queued refresh contexts.

While foreground navigation or another refresh is active, adjacent pending calls coalesce only when their effective headers match. Header names are case-insensitive; the ordering of distinct names does not matter. Values retain standard Headers semantics. Matching calls share a promise; different headers produce separate requests in call order, never a merged header set. For example, queued contexts A, B, A remain three requests. Calls during a running refresh schedule trailing work, not a subscription to the running attempt. With no options, the existing coalescing behavior remains.

type NavigationRefreshOptions = {
  headers?: HeadersInit;
};

headers accepts a string-valued record, an array of [name, value] pairs, or a Headers instance. Primate snapshots it synchronously when refresh() is called, so later mutation cannot change a deferred request or its replacement. Headers apply only to that refresh context, not to later no-options refreshes or ordinary navigation. Normal browser header restrictions still apply.

Primate always sets Accept: application/json and Primate-Navigation: true, overriding those two custom header names case-insensitively. These effective headers determine coalescing. Invalid header names or values throw a TypeError during the snapshot, before queuing work.

await navigate.refresh({ headers: { "X-Refresh-Context": "background" } });

Headers are application-defined; Primate does not interpret activity markers or automatically classify refreshes as passive requests.

after(listener: NavigationListener): () => void;

Registers a browser-global listener for successful view-changing Primate navigations. It runs after the destination view updates and receives the current absolute URL and cloned entry state. It does not run for failures, superseded/full-document, hash-only, or shallow navigation. Returns an unsubscribe function; repeated unsubscribe calls simply remove the same listener again.

Listener passed to navigate.after().

type NavigationListener = (
  detail: NavigationEventDetail,
) => void;

Listeners run synchronously from the primate:navigation-end browser event.

Details passed to navigation listeners after a view change.

type NavigationEventDetail = {
  source: NavigationSource;
  state: unknown;
  url: string;
};
type NavigationSource = "form" | "history" | "navigate" | "refresh";

Enhanced forms report "form", Back/Forward reports "history", links and direct navigate() calls report "navigate", and successful refreshes report "refresh".

state(): unknown;

Returns a structured clone of the current entry's ephemeral state, or undefined when none exists or the entry belongs to another client partition. Mutating the returned value does not mutate stored entry state.

Error and fallback behavior

Invalid URLs and structuredClone failures reject navigate(). SPA transport, response, and rendering failures are logged with console.warn and resolve the navigation promise without changing history. A later navigation supersedes an earlier request; stale responses are discarded.

The entrypoint has no server-conditioned implementation. Calling these members during SSR accesses browser APIs and is unsupported.

Previous
Store
Next
Events