API Reference

Every export an application uses, grouped by what it does, with the guide that explains it. Look a symbol up here when you know the name but not the page.

Import Paths

Every pracht package is ESM-only, so tsc needs "moduleResolution": "bundler" (or "node16"/"nodenext") — see TypeScript settings pracht requires.

Almost everything comes from @pracht/core. Its browser condition resolves client bundles to a client-safe subset of the same specifier, with its own types, so a server-only export such as handlePrachtRequest is a compile error in client code. create-pracht enables the condition in tsconfig.client.json and includes src/**/*.d.ts there, so client code also sees the types pracht typegen generates. Keep both in custom client configs:

tsconfig.client.json
{
  "compilerOptions": {
    "moduleResolution": "bundler",
    "customConditions": ["browser"]
  },
  "include": ["src/routes/**/*", "src/shells/**/*", "src/islands/**/*", "src/**/*.d.ts"]
}

The base tsconfig.json leaves the condition off for server code and tests, and the generated typecheck script checks both programs.

Specifier Use
@pracht/core Application code, client and server alike
@pracht/core/server Server-only entry points, mostly for adapters and generated server entries
@pracht/core/client initClientRouter() and hydration state, for custom client entries
virtual:pracht/capabilities The generated browser capability client. See Capabilities

Companion packages are separate installs; see Companion Packages.

Defining the App

Export Description
defineApp(config) The route manifest. See Configuration
route(path, file, meta?) One route. See Routing
group(meta, routes) Shared meta for a subtree of routes
timeRevalidate(seconds) ISG time-based revalidation policy. See Rendering Modes
webhookRevalidate() ISG on-demand revalidation policy

Constraints

Declarative invariants over the resolved graph, enforced by pracht verify. See Coding Agents.

Export Description
requireMiddleware(pattern, name) Every matching route must run this middleware
requireShell(pattern, name) Every matching route must use this shell
requireRenderMode(pattern, mode) Every matching route must use this render mode
forbidRenderMode(pattern, mode) No matching route may use this render mode
requireHead(pattern) Every matching route must export head()

Components

Export Description
<Link> Typed client-side navigation. See Routing
<Form> Progressive form submission to an API route or a capability. See Forms
<Script> Third-party scripts with a loading strategy. See Data Loading
<Suspense>, lazy() Code-split a subtree with a fallback. See Rendering Modes
<ErrorBoundary> Catch render errors in a subtree. See Data Loading
forwardRef() Preact's forwardRef, re-exported so an app needs one Preact import path

Loader Data

Export Description
defer(promise) Mark slow loader data for concurrent resolution. See Data Loading
use(value) Read a Deferred<T>, promise, or settled value inside <Suspense>
Deferred<T> The typed marker returned by defer()
SearchArgs<typeof search> Types args.search as the route's search schema output. See Routing

Server Islands

Components in src/server-islands/ rendered per request inside cached pages. See Server Islands.

Export Description
useServerIslandData<typeof loader>() Inside a server island component: the value its loader returned
ServerIslandLoaderArgs<TContext, TProps> Argument of a server island loader: the page's route args plus the server island's props (untrusted input)
ServerIslandProps Intersect into a server island's props for the framework-owned fallback
export const serverIslands Route or shell module export listing the server islands it renders; the endpoint runs only listed ones
ServerIslandLoaderData<T> The data type useServerIslandData<T>() resolves to

Hooks

Export Returns Description
useRouteData(routeId?) The loader's data The active route's loader result. Pass the route id to type it; any other route's id throws. See Data Loading
useShellData(shell?) The shell loader's data, or undefined The loader result of the active route's shell, readable from the shell and its routes. Pass the shell name to type it; any other shell's name throws. See Shells
useParams() Record<string, string> Matched dynamic segments. See Routing
useLocation() { pathname, search } The current URL as the visitor sees it, deploy base included
useSearchParams() ReadonlyURLSearchParams The query string, reactively. Mutating it throws — navigate instead
useSearch(routeId?) The parsed query The active route's search schema output, or the raw query without one. See Routing
useNavigate() (to, options?) => Promise<void> Imperative navigation, by path or route object
useNavigation() { state, location?, formData? } Pending state for the current navigation or <Form> submission: "idle", "loading", or "submitting"
useBlocker(shouldBlock, options?) { state, location, proceed, reset } Stop a navigation before it commits, e.g. unsaved changes. See Data Loading
useRevalidate() () => void Re-run the active route's loader and its shell's
useIsHydrated() boolean false during SSR and the first client render, true after
useEventSource(url, options?) { status, data, lastEventId } Subscribe to a server-sent event stream. status is "connecting", "open", or "closed". See Server-Sent Events & WebSockets
useCapability(name) { call, data, error, pending, reset } Call state for a user-triggered capability call. From virtual:pracht/capabilities
Export Description
prefetch(target) Warm a route's chunks and route-state JSON. See Prefetching
createHref(routes) Build an href() helper from route definitions. pracht typegen generates one for you
buildHref(...) Resolve a route id and params to a URL path
redirect(location, options?) Throw from a loader or middleware to redirect. See Middleware
notFound(message?) Throw to render the app's 404 page. See Data Loading
PrachtHttpError Throw for a structured error response with a status

Deploy base

For hand-written URLs only — <Link>, href(), and apiFetch() already apply the base. See Sub-Path Deploys.

Export Description
PRACHT_BASE The configured base, with leading and trailing slashes. "/" by default
withBase(path) Route path → URL path
stripBase(pathname) URL path → route path, or null when the URL is outside the base

API Routes

Export Description
defineApi(config) Schema-validated handlers with typed args. See API Validation
json(value, init?) A typed JSON Response
apiFetch(path, options?) Typed client for your own API routes
ApiFetchError Thrown by apiFetch() on a non-2xx response
formDataToRecord(formData) FormData → a plain record, arrays for repeated fields
searchParamsToRecord(params) The same for URLSearchParams
isApiValidationErrorBody(body) Narrow a response body to the standard validation-error shape

Streaming

See Server-Sent Events & WebSockets.

Export Description
createEventStream(init?) A server-sent events Response with a send/close handle
serializeEventStreamMessage(message) Format one SSE frame by hand
isUpgradeRequest(request) True for a WebSocket upgrade request

Capabilities and Agents

See Capabilities and Agent Trust.

Export Description
invokeCapability(name, input, ctx) Trusted server-side call, including private capabilities
createCapabilityTestHost(options?) Drive capabilities in tests without booting a server
setCapabilityAuditHook(hook) Receive a structured event for every capability call (single slot)
addCapabilityAuditListener(name, hook) Add a named audit sink; the same name replaces it. Returns an unsubscribe
setCapabilityApprovalStore(store) Persist approvals for the confirmation flow
createMemoryApprovalStore(options?) An in-memory store, for development and tests
setCapabilityApprovalPrincipalResolver(fn) Decide which principal an approval belongs to
setCapabilityConfirmationSecret(secret) Sign confirmation tokens
defineCapability(config) Define one capability. From @pracht/capabilities

Environment

See Environment Variables.

Export Description
publicEnv Public variables, safe in the client bundle
PRACHT_PUBLIC_ENV_PREFIX The prefix that marks a variable public
filterPublicEnv(env) Reduce an env object to its public entries
serverEnv Server-only variables. From @pracht/core/env/server
setServerEnv(env) Supply the server env from an adapter that has no process.env

Fonts

Export Description
defineFont(options) Self-hosted font with preload and font-display handling. See Fonts

Performance

Export Description
useWebVitals(reporter) Lazily report CLS, FCP, INP, LCP, and TTFB from a client component. See Performance

Sessions

From @pracht/session. It runs on every adapter. See Authentication.

Export Description
createSessionStorage<Data>({ cookie, store, rolling }) The app's session storage. Without store, data is sealed (AES-256-GCM) in the cookie; with one, the cookie holds only a sealed id. rolling: true makes maxAge an idle timeout
sessionMiddleware(storage, options?) Loads the session onto context.session and commits changes after the chain. Does not gate
requireSession(storage, options?) The same, plus a gate: page requests redirect to loginPath, API requests get 401
createMemorySessionStore() In-memory SessionStore for tests and dev. Not a production store
hashPassword(password, options?) PBKDF2-HMAC-SHA256 hash that records its own parameters
verifyPassword(password, stored) Constant-time check against a stored hash
withSetCookie(response, header) Append a Set-Cookie and return the response, or a copy when its headers are immutable; use the returned value

cookie takes { name?, secrets, maxAge?, path?, domain?, sameSite?, secure?, httpOnly? }; name defaults to "__Host-session". List secrets newest first: the first seals, all of them open, so you rotate by prepending a new secret. Secure is on except over plain http from a loopback host, and always on for a __Host-/__Secure- name.

Expiry is absolute from the last write, and the middleware commits only when the session changed.

SessionStorage method Description
getSession(request) The session for a request. An invalid or expired cookie yields a fresh empty session instead of throwing
commitSession(session, options?) Seal and return the Set-Cookie value. Throws when a cookie session exceeds 4 KB
commit(session, response, options?) The same, appended to a response (existing Set-Cookie headers preserved)
destroySession(session) / destroy(session, response) Delete the store record and expire the cookie
isDirty(session) Whether the session changed this request
Session member Description
id Random 128-bit session id
data Read-only snapshot; does not consume flash values
get(key) Read a value — and consume it, if it was flashed
set(key, value) / unset(key) / has(key) Durable writes and presence
flash(key, value) Write a value that survives exactly one read
regenerate() New id, same data, old store record dropped. Call it on every privilege change, such as login, to prevent session fixation
SessionStore method Description
get(id) The stored record, or null when unknown or expired
set(id, data, expiresAt) Persist the record. expiresAt is Date.now()-style milliseconds
delete(id) Remove the record; must not throw on an unknown id

Companion Packages

Package Key exports Guide
@pracht/i18n defineI18n, createDictionaries, t, tPlural, interpolate, matchAcceptLanguage, parseAcceptLanguage i18n Reference
@pracht/image Image, getImageProps Images
@pracht/content defineCollection, llmsTxtArtifacts, rawContentArtifacts, parseFrontmatter Content Collections
@pracht/markdown defineMarkdownCollection Content Collections
@pracht/openapi defineOpenApi, getOpenApiDescriptor, generateOpenApiDocument, createOpenApiUiHtml OpenAPI
@pracht/query createQueryRoot, getQueryClient, @pracht/query/root TanStack Query
@pracht/session See Sessions Authentication
@pracht/capabilities defineCapability Capabilities
@pracht/test createLoaderArgs, runMiddleware, createFormRequest, submitForm, readJson, readRedirect Testing

Not Listed Here

@pracht/core also exports adapter-facing internals — handlePrachtRequest, prerenderApp, buildAppGraph, handleMcpRequest, the revalidation helpers, the app-graph serializers. Applications rarely need them; the matching adapter or CLI command usually does the job.