Reference
API Reference.
Generated from JSDoc in @nativefragments/core and @nativefragments/lit. Each symbol links back to the concept guide that explains it.
@nativefragments/core/server
Server HTML
Tagged-template HTML rendering that escapes by default, with helpers for attributes and embedded JSON. Source ↗
raw
raw(value?) → RawHtml
Mark a value as trusted HTML. Use this only for framework-generated markup or content that has already been validated. Ordinary interpolated values in html are escaped by default.
Parameters
-
valueunknown optional = ""HTML to insert without escaping.
Returns
RawHtml — Trusted HTML wrapper.
html`<div>${userInput}</div>` // escaped — safe
html`<div>${raw(userInput)}</div>` // bypasses escaping — trusted HTML only
See also Agent-Friendly Apps
escapeHtml
escapeHtml(value) → string
Escape a value for safe insertion into HTML text or attribute context.
Parameters
-
valueunknownValue to escape.
Returns
string — Escaped HTML string.
html
html(strings, ...values) → RawHtml
Server-side HTML template tag with escaped interpolation by default. Arrays are flattened, null, undefined, and false become empty strings, and trusted values returned by html, raw, or attrs are inserted as HTML without being re-escaped.
Parameters
-
stringsTemplateStringsArrayTemplate literal string parts.
-
values...unknownInterpolated values.
Returns
RawHtml — Rendered HTML wrapper.
import { html, raw } from "@nativefragments/core/server";
// Interpolations are escaped by default — user input is safe.
const card = (post) => html`<article>
<h2>${post.title}</h2>
${raw(post.bodyHtml)}
</article>`;
See also Components
jsonScript
jsonScript(value) → string
Serialize JSON for safe embedding inside an inline script tag. < characters are escaped so embedded JSON cannot accidentally terminate the script element.
Parameters
-
valueunknownValue to serialize.
Returns
string — JSON string safe for script text.
import { html, jsonScript, raw } from "@nativefragments/core/server";
// Safe to embed in an inline script — "<" is escaped.
html`<script type="application/json">${raw(jsonScript(state))}</script>`;
attrs
attrs(attributes?) → RawHtml
Build escaped HTML attributes from an object. false, null, and undefined values are omitted. true values render as boolean attributes. Attribute names must be valid HTML-like names.
Parameters
-
Attribute map.
Returns
RawHtml — Trusted HTML attribute string.
import { attrs, html } from "@nativefragments/core/server";
// false / null / undefined are dropped; true renders a boolean attribute.
html`<button ${attrs({ disabled: post.locked, "data-id": post.id })}>Edit</button>`;
@nativefragments/core/server
Server Routing
Define routes, match requests, and render full pages or individual named fragments. Source ↗
fragment
fragment(name, definition) → FragmentDefinition
Create a named fragment definition. Use this when a route has a nested region with its own navigation. The returned object can be registered in route(..., { fragments: [item] }) and its attributes can be reused on links and target containers.
Parameters
-
namestringFragment slot name.
-
definitionFragmentRenderer | Omit<FragmentDefinition, "name" | "attrs" | "prefetchAttrs">Fragment renderer or full fragment definition.
Returns
FragmentDefinition — Fragment definition.
-
namestringFragment slot name.
-
renderFragmentRendererFragment renderer.
-
Loading renderer used by deferred HTML streaming.
-
Error renderer used when a deferred fragment fails after its HTML response has started.
-
timeoutnumber optionalMaximum deferred render time in milliseconds.
-
Attributes for links and target containers using this fragment slot.
-
prefetchAttrs(mode?: "intent" | "visible" | "load" | "none", attributes?: import("./html.js").HtmlAttrs) => import("./html.js").RawHtmlAttributes for links using this fragment slot with a prefetch mode.
import { fragment, route } from "@nativefragments/core/server";
const panel = fragment("settings-panel", renderPanel);
route("/settings/profile", {
render: settingsPage,
fragments: [panel], // exposes the named slot for partial swaps
});
See also Fragments
route
route(path, definition) → Route
Create a normalized route definition.
Parameters
-
pathstringURL path for the route. Use
:namesegments for path params, for example/posts/:slug. -
definitionRouteDefinitionRoute metadata and render functions.
-
Function that returns metadata for the route.
-
statusnumber optional = 200Status used for rendered HTML responses.
-
headersRecord<string, string> | ((context: RouteContext) => Record<string, string> | Promise<Record<string, string>>) optionalHeaders merged into rendered HTML responses after adapter defaults.
-
POST handler for no-JavaScript mutations. Must return a native Response, usually a 303 redirect.
-
render(context: RouteContext) => string | import("./html.js").RawHtml | Response | Promise<string | import("./html.js").RawHtml | Response>Function that renders route body HTML.
-
Named fragment renderers used by nested fragment slots.
-
Returns
Route — Normalized route.
import { html, route } from "@nativefragments/core/server";
// :slug becomes ctx.params.slug
export const post = route("/blog/:slug", {
meta: (ctx) => ({ title: ctx.params.slug }),
render: (ctx) => html`<h1>${ctx.params.slug}</h1>`,
});
See also Routing
redirect
redirect(location, status?) → Response
Create a redirect response.
Parameters
-
locationstring | URLRedirect destination.
-
statusnumber optional = 302Redirect status.
Returns
Response — Native redirect response.
readSearch
readSearch(searchParams, defaults) → T
Read string query parameters with defaults. Each returned key is searchParams.get(key) when it is a non-empty string, otherwise the default value.
Parameters
-
searchParamsURLSearchParamsQuery parameters.
-
defaultsTDefault values.
Returns
T — Query values merged with defaults.
createRoutes
createRoutes(routes) → { all: Route[], match(pathname: string): Route | null }
Create a route manifest that can match normalized paths. Exact static routes win first, then parameterized routes are matched in declaration order.
Parameters
-
routesRoute[]Route definitions.
Returns
{ all: Route[], match(pathname: string): Route | null } — Route manifest.
import { createRoutes } from "@nativefragments/core/server";
const manifest = createRoutes([home, post]);
manifest.match("/blog/hello"); // → the post route, params.slug = "hello"
See also Routing
fragmentMeta
fragmentMeta(meta) → import("./html.js").RawHtml
Render fragment metadata for the browser fragment router.
Parameters
-
metaRouteMetaMetadata to embed in the fragment response.
-
titlestring optionalDocument title.
-
descriptionstring optionalMeta description.
-
canonicalstring optionalCanonical URL.
-
alternates{ hreflang: string, href: string }[] optionalAlternate language URLs for
<link rel="alternate" hreflang="...">.
-
Returns
import("./html.js").RawHtml — Script tag containing serialized metadata.
See also Fragments
renderRoute
renderRoute(options) → Promise<{ body: string, meta: Required<Pick<RouteMeta, "title" | "description" | "canonical">> & RouteMeta, deferred: unknown[], status: number, headers: Record<string, string> } | { response: Response }>
Render a matched route and normalize metadata defaults.
Parameters
-
options{ match: Route, request: Request, slot?: string | null, deferredTimeout?: number | null }Render options. When
slotmatches a registered named fragment, only that fragment renderer is used. Calls tocontext.defer()always collect deferred work for the adapter to stream or inline.
Returns
Promise<{ body: string, meta: Required<Pick<RouteMeta, "title" | "description" | "canonical">> & RouteMeta, deferred: unknown[], status: number, headers: Record<string, string> } | { response: Response }> — Rendered route.
renderFragment
renderFragment(rendered) → import("./html.js").RawHtml
Render a fragment response body with embedded metadata.
Parameters
-
rendered{ body: string, meta: RouteMeta }Rendered route body and metadata.
Returns
import("./html.js").RawHtml — Fragment HTML.
notFoundRoute
notFoundRoute
Default 404 route used by adapters when a route is not matched.
Type
{Route}
See also Routing
errorRoute
errorRoute
Default 500 route used by adapters when a route render fails.
Type
{Route}
@nativefragments/core/server
Server API
apiRoute
apiRoute(method, path, handler) → ApiRoute
Create a normalized API route. Paths use the same :param and trailing :rest* segment syntax as page routes.
Parameters
-
methodstringUpper-case HTTP method.
-
pathstringAPI path pattern.
-
handlerApiHandlerAPI handler.
Returns
ApiRoute — Normalized API route.
createApi
createApi(routes, options?) → { fetch(request: Request, env?: Record<string, unknown>, context?: unknown): Promise<Response> }
Create a Fetch-compatible API router.
Parameters
-
routesApiRoute[]API route definitions.
-
methodstringUpper-case HTTP method.
-
pathstringNormalized API route path.
-
handlerApiHandlerAPI route handler.
-
-
options{ onError?: (event: { error: unknown, request: Request, route?: ApiRoute }) => void } optional = {}API options.
Returns
{ fetch(request: Request, env?: Record<string, unknown>, context?: unknown): Promise<Response> } — Fetch-compatible API router.
@nativefragments/core/cloudflare
Cloudflare Adapter
Turn a route manifest into a Cloudflare Worker that serves pages, fragments, static assets, and API routes. Source ↗
createCloudflareHandler
createCloudflareHandler(options) → { fetch(request: Request, env: Record<string, unknown>): Promise<Response> }
Create a Cloudflare Worker module for a Native Fragments app. Static assets are served from the configured assets binding. Normal document requests render the app shell. Requests with x-fragment: true return the route body plus fragment metadata, using framed HTML streaming when the route has deferred content. Requests under apiPrefix are delegated to the optional API router before app route matching.
Parameters
-
optionsCloudflareHandlerOptionsWorker adapter options.
-
routesRoute[]App route definitions.
-
shell(rendered: { body?: import("../server/html.js").RawHtml, meta: object, nonce?: string }) => string | import("../server/html.js").RawHtml | { before: string | import("../server/html.js").RawHtml, after: string | import("../server/html.js").RawHtml } | Promise<string | import("../server/html.js").RawHtml | { before: string | import("../server/html.js").RawHtml, after: string | import("../server/html.js").RawHtml }>Function that wraps a rendered route body in a full HTML document.
-
api{ fetch(request: Request, env: Record<string, unknown>, context?: unknown): Promise<Response> | Response } | import("../server/api.js").ApiRoute[] optionalOptional Web Standards API router or array of
apiRoute()definitions. Hono apps work here because they expose a compatiblefetchmethod. -
apiPrefixstring optional = "/api"URL prefix handled by
api. -
Optional 404 route.
-
Optional 500 route.
-
onError({ error, request, phase }: { error: unknown, request: Request, phase: "route" | "error-route" | "api" }) => void optionalError hook for caught route, error-route, and API failures.
-
assetsBindingstring optional = "ASSETS"Cloudflare assets binding name.
-
deferredTimeoutnumber | null optional = 15000Default timeout in milliseconds for each deferred fragment renderer. Set
nullto disable. -
contentSecurityPolicystring | false | ((options: { nonce: string, request: Request }) => string | false) optionalContent Security Policy header. Defaults to
frame-ancestors 'self'. Pass a function to build a nonce-based strict policy.
-
Returns
{ fetch(request: Request, env: Record<string, unknown>): Promise<Response> } — Cloudflare Worker module.
// worker.js
import { createCloudflareHandler } from "@nativefragments/core/cloudflare";
import { routes } from "./site/routes.js";
import { shell } from "./site/shell.js";
export default createCloudflareHandler({ routes, shell });
See also API Routes · Getting Started
@nativefragments/core/client/router.js
Browser Router
Upgrade same-origin links into streamed fragment navigation with explicit control, caching, and lifecycle events. Source ↗
startRouter
startRouter(options?) → Readonly<FragmentRouter>
Start document navigation and return a small imperative controller. Links and opted-in GET forms retain their native behavior when JavaScript is unavailable. While active, same-origin navigation is upgraded with streamed HTML fragments, history, metadata, focus, scrolling, and prefetching.
Parameters
-
optionsFragmentRouterOptions optional = {}Router options.
-
targetstring | Element optional = "#content-slot"Primary navigation target.
-
cacheTtlnumber optional = 30000Completed fragment cache lifetime.
-
Default automatic prefetch policy.
-
viewTransitionsboolean optional = trueUse View Transitions when available.
-
signalAbortSignal optionalAborting this signal tears down the router.
-
Returns
Readonly<FragmentRouter> — Router controller.
-
navigate(href: string | URL, options?: NavigateOptions) => Promise<void>Navigate to a route or named fragment.
-
prefetch(href: string | URL, options?: FragmentRequestOptions) => Promise<void>Warm a completed fragment in the shared cache.
-
invalidate(href?: string | URL, options?: InvalidateOptions) => voidDrop matching cached and in-flight fragments, or all fragments when omitted.
import { startRouter } from "@nativefragments/core/client/router.js";
const router = startRouter({ prefetch: "intent" });
await router.navigate("/blog/hello");
router.invalidate("/blog/hello");
See also Fragments
@nativefragments/core/client/worker.js
Web Workers
A tiny RPC layer over Web Workers for moving expensive work off the main thread. Source ↗
transferResult
transferResult(payload, transfer?) → { payload: T, transfer: Transferable[], [transferMarker]: true }
Wrap a worker response with Transferable objects.
Parameters
-
payloadTResponse payload.
-
transferTransferable[] optional = []Transferable objects to move.
Returns
{ payload: T, transfer: Transferable[], [transferMarker]: true }
import { exposeWorker, transferResult } from "@nativefragments/core/client/worker.js";
exposeWorker({
// Move the buffer instead of copying it.
bytes: (buffer) => transferResult(buffer, [buffer]),
});
See also Workers
workerClient
workerClient(worker, options?) → NativeWorkerClient
Create a tiny RPC client for a dedicated Web Worker.
Parameters
-
workerWorkerWorker instance.
-
optionsWorkerClientOptions & { owned?: boolean } optional = {}Client options.
-
timeoutnumber optional = 30000Request timeout in milliseconds.
-
ownedboolean optional
-
Returns
NativeWorkerClient — Worker client.
-
call(type: string, payload?: unknown, transfer?: Transferable[]) => Promise<unknown>Call a named worker handler.
-
dispose() => voidReject pending calls, remove listeners, and terminate workers constructed by
createWorkerClient. -
workerWorkerThe wrapped Worker instance.
See also Workers
createWorkerClient
createWorkerClient(workerOrUrl, options?) → NativeWorkerClient
Create a module worker and wrap it with workerClient.
Parameters
-
workerOrUrlstring | URL | WorkerExisting Worker or worker module URL.
-
optionsWorkerClientOptions & { workerOptions?: WorkerOptions } optional = {}Client and Worker constructor options.
-
timeoutnumber optional = 30000Request timeout in milliseconds.
-
workerOptionsWorkerOptions optional
-
Returns
NativeWorkerClient — Worker client.
import { createWorkerClient } from "@nativefragments/core/client/worker.js";
const search = createWorkerClient("/build/search-worker.js");
const hits = await search.call("search", { rows, query: "native" });
See also Workers
exposeWorker
exposeWorker(handlers, scope?) → () => void
Expose named handlers inside a dedicated Web Worker.
Parameters
-
handlersRecord<string, (payload: unknown, context: { event: MessageEvent, type: string }) => unknown | Promise<unknown>>Worker handlers keyed by message type.
-
scopeNativeWorkerScope optional = globalThisWorker global scope.
-
postMessage(message: unknown, transfer?: Transferable[]) => voidPost a message to the paired thread.
-
addEventListener(type: "message", listener: (event: MessageEvent) => void) => voidRegister a message listener.
-
removeEventListener(type: "message", listener: (event: MessageEvent) => void) => voidRemove a message listener.
-
Returns
() => void — Cleanup function.
// client/search-worker.js
import { exposeWorker } from "@nativefragments/core/client/worker.js";
exposeWorker({
search: ({ rows, query }) =>
rows.filter((row) => row.title.toLowerCase().includes(query.toLowerCase())),
});
See also Workers
@nativefragments/lit/server
Lit SSR
Render Lit templates and custom elements as hydratable server HTML. Source ↗
renderLit
renderLit(value) → Promise<import("@nativefragments/core/server").RawHtml>
Render a Lit template or component tree to trusted server HTML. Component modules must be imported by the Worker so their custom element definitions are registered in Lit's server DOM shim.
Parameters
-
valueunknownLit template value to render.
Returns
Promise<import("@nativefragments/core/server").RawHtml>
import { renderLit } from "@nativefragments/lit/server";
import { html } from "lit";
import "../../client/components/app-card.js";
export const card = () =>
renderLit(html`<app-card>Ready</app-card>`);
See also Lit Components
Types
Shared object shapes referenced by the functions above.
RawHtml
{ [RAW]: true, value: string, toString(): string }
HtmlAttrs
Record<string, string | number | boolean | null | undefined>
RouteContext
object
Properties
-
requestRequestOriginal request.
-
signalAbortSignalRequest cancellation signal.
-
urlURLParsed request URL.
-
queryURLSearchParamsParsed query parameters from
url.searchParams. -
paramsRecord<string, string>Path parameters captured from a route pattern like
/posts/:slug. -
defer(fragment: FragmentDefinition | string, attributes?: import("./html.js").HtmlAttrs) => import("./html.js").RawHtmlRender a stable loading boundary and collect a named fragment for deferred HTML streaming during document loads and browser fragment navigation.
FragmentRenderer
(context: RouteContext) => string | import("./html.js").RawHtml | Response | Promise<string | import("./html.js").RawHtml | Response>
FragmentLoadingRenderer
(context: RouteContext) => string | import("./html.js").RawHtml
FragmentErrorRenderer
(error: unknown, context: RouteContext) => string | import("./html.js").RawHtml | Promise<string | import("./html.js").RawHtml>
Route
RouteDefinition & { path: string, params?: Record<string, string> }
ApiContext
object
Properties
-
requestRequestOriginal request.
-
envRecord<string, unknown>Runtime environment bindings.
-
contextunknownRuntime execution context.
-
urlURLParsed request URL.
-
queryURLSearchParamsParsed query parameters from
url.searchParams. -
paramsRecord<string, string>Path parameters captured from the API route.
-
signalAbortSignalRequest cancellation signal.
ApiHandler
(context: ApiContext) => unknown | Response | Promise<unknown | Response>
PrefetchMode
"none" | "intent" | "visible" | "load"
FragmentRequestOptions
object
Properties
-
slotstring optionalNamed fragment target.
-
signalAbortSignal optionalAbort this request consumer.
InvalidateOptions
object
Properties
-
slotstring optionalLimit invalidation to one named fragment target.