Skip to content

API Reference

All public exports from @cmj/juice/runtime, @cmj/juice/node and @cmj/juice/client, with when and why you would use each one.

@cmj/juice/runtime

createRouter(manifest, options?)

The core function. Takes a flight manifest and optional configuration, returns a WinterCG-compatible fetch handler.

import { createRouter } from '@cmj/juice/runtime';
import manifest from './flight-manifest.json';

const handler = createRouter(manifest, {
  root: import.meta.url,
  streaming: 'shell',
});

// handler: (req: Request) => Promise<Response>

When to use: always. This is the entry point of every Juice app. See Router Options for all configuration options.

redirect(url, status?, options?)

Throws a redirect Response. Works in components, server actions, and middleware. Default status is 302 (Found). Pass options.headers when the redirect also needs response headers such as Set-Cookie.

import { redirect } from '@cmj/juice/runtime';

// In a server component
export default async function Product({ params }: { params: { id: string } }) {
  const product = await db.find(params.id);
  if (product.archived) {
    redirect('/products');       // 302 redirect
  }
  if (!product) {
    redirect('/not-found', 303); // 303 redirect (POST-Redirect-GET)
  }
  return <h1>{product.name}</h1>;
}

// In a server action
async function login(formData: FormData) {
  'use server';
  // ... validate credentials
  const sessionCookie = await createSessionCookie();
  redirect('/dashboard', 303, {
    headers: { 'Set-Cookie': sessionCookie },
  });  // Always use 303 after form submissions
}

Coming from Next.js: same throw-based control flow. redirect()throws, so it must not be called inside a try/catch that swallows the error.

cache(fn)

Wraps an async function with request-scoped memoization. Deduplicates calls with the same arguments within a single request using identity-based keys.

import { cache } from '@cmj/juice/runtime';

const getUser = cache(async (userId: string) => {
  return await db.users.find(userId);
});

// Two calls with the same userId in the same request = one DB query
const user1 = await getUser('42');
const user2 = await getUser('42'); // Returns cached promise, no second query

When to use: any async function called from multiple components in the same render. Typically data-fetching functions. Do not use for functions with side effects.

Coming from Next.js: Next.js patches fetch() for automatic deduplication. Juice does not touch fetch(). You explicitly wrap functions you want deduplicated.

cache(fn, { key, revalidate?, expire?, tags? })

With options, results are also shared across requests through the router's CacheAdapter. Stale entries (older than revalidate seconds) are served while a fresh value is computed in the background. The returned function is always async. Arguments must be plain data; they form the cache key.

const getProduct = cache(
  async (id: string) => db.products.find(id),
  { key: 'product', revalidate: 60, tags: (id) => [`product:${id}`] },
);

Coming from Next.js: like unstable_cache, but the key is one explicit string and storage is whatever adapter you pass to createRouter().

revalidateTag(tag)

Invalidates every cross-request entry carrying tag. Each cache(fn, { key }) function is tagged with its own key. Returns a promise that resolves once the adapter has stored the invalidation.

await revalidateTag('product:42'); // one product
await revalidateTag('product');    // every getProduct() entry

Called inside a server action, the tags are also sent back as X-Juice-Revalidated, and the client refreshes the slices tagged with them.

<Slice href tags? defer? fallback? refresh? />

Server island: renders the route at href inside the page, in a <juice-slice> element that refreshes by itself after server actions and on useRouter().refresh(). Params and search params come from the href; identity from the request. See Partial Rendering.

import { Slice } from '@cmj/juice/runtime';

<Slice href="/dashboard/cart" tags={['cart']} />
<Slice href="/widgets/weather?city=lon" defer fallback={<p>Loading…</p>} />
  • href — same-origin route URL, resolved against the page URL.
  • tags — matched against revalidateTag() calls and refresh(tag); default [href]. cart matches cart and cart:*.
  • defer — true fetches after the page loads, 'visible' when the slice scrolls into view.
  • fallback — shown while deferring or suspending; default the route's pending.tsx.
  • refresh — 'manual' stops a form inside the slice from refreshing it.

memoryCache(options?) / kvCache(kv, options?)

Built-in adapters. memoryCache({ maxEntries = 1000, clone = true }) is a per-process LRU and the default. kvCache(env.CACHE, { prefix }) stores JSON in a Cloudflare Workers KV namespace.

setContext(req, key, value)

Attaches a value to the request's context store. The key can be a string or a typed ContextKey.

import { setContext } from '@cmj/juice/runtime';

// With a string key (value type is unknown when reading)
setContext(req, 'userId', '42');

// With a typed key (value type is enforced)
import { createContextKey } from '@cmj/juice/runtime';
const userKey = createContextKey<User>('user');
setContext(req, userKey, user); // TypeScript enforces user: User

When to use: in middleware, to pass data to route components. Auth middleware sets the user, database middleware sets the connection pool.

getContext(req, key)

Reads a value from the request's context store. Returns T | undefinedwhen using a typed ContextKey<T>, or unknown with string keys.

import { getContext } from '@cmj/juice/runtime';
import { userKey } from '../context-keys';

export default function Dashboard({ request }: { request: Request }) {
  const user = getContext(request, userKey); // User | undefined
  return <h1>Welcome, {user?.name}</h1>;
}

createContextKey<T>(name)

Creates a typed context key. The name parameter is used for debugging. The type parameter T is the value type, enforced at compile time. At runtime, this is just an object with a name property.

import { createContextKey } from '@cmj/juice/runtime';

export const userKey = createContextKey<User>('user');
export const dbKey = createContextKey<Database>('db');
export const requestIdKey = createContextKey<string>('requestId');

createActionContext(req, params?)

Creates an ActionContext for testing server actions outside of a real request. Useful in unit tests.

import { createActionContext } from '@cmj/juice/runtime';

// In a test
const ctx = createActionContext(
  new Request('http://localhost/product/42', { method: 'POST' }),
  { id: '42' }
);
const result = await myAction(formData, ctx);

eventStream(signal, source, options?)

Creates a text/event-stream Response for Server-Sent Events. The source can be a callback that receives send() or an async iterable that yields SSEEvent objects. The helper wires req.signal to cleanup and sends keep-alive comments every 25 seconds by default.

import { eventStream } from '@cmj/juice/runtime';

export function GET(req: Request) {
  return eventStream(req.signal, async function* () {
    yield { event: 'ready', data: { ok: true } };
    yield { data: 'hello' };
  }, {
    keepAlive: 10_000,
  });
}

When to use: live notifications, AI token streams, progress updates, or any one-way event feed where WebSockets would be unnecessary.

createChannel(source?, options?)

Shared event sources for eventStream() routes. The source (publish, key) => cleanup runs once per key: started for the first subscriber of that key, shared by every other subscriber of it, stopped (its cleanup run) when the last one leaves. Without a source the channel is plain pub/sub fed by publish(). Define it at module level, subscribe per request.

import { createChannel, eventStream } from '@cmj/juice/runtime';

const builds = createChannel((publish, buildId) => {
  const timer = setInterval(async () => {
    publish({ id: String(Date.now()), event: 'status', data: await db.builds.find(buildId) });
  }, 1000);
  return () => clearInterval(timer);
}, { buffer: 20 });

export function GET(req: Request, ctx: ActionContext) {
  return eventStream(req.signal, builds.subscribe(ctx.params.id, req.headers.get('Last-Event-ID')));
}

The returned Channel has:

  • subscribe(key, lastEventId?) -- a callback source for eventStream(): registers send, returns the unsubscribe function. With lastEventId, replays missed events from the buffer first.
  • events(key, lastEventId?) -- the same subscription as an AsyncIterable<SSEEvent>, to pass to eventStream() directly.
  • publish(key, event) -- delivers to every subscriber of the key on every instance sharing the broadcast adapter. Resolves once the adapter accepted it.
  • subscribers(key) -- number of subscribers in this process.

Options: buffer (events kept per key for Last-Event-ID replay, default 0: the runtime otherwise does nothing with that header), linger (ms to keep a source and its buffer after the last subscriber leaves, default 0) and broadcast (a BroadcastAdapter, default memoryChannel()). See the SSE guide.

memoryChannel() / redisChannel(client, options?)

Broadcast adapters for createChannel(). memoryChannel() is in-process and the default. redisChannel(client, { prefix }) uses Redis pub/sub through node-redis, Bun.redis or any client with publish, subscribe, unsubscribe and duplicate; it adds no dependency.

Type Exports (@cmj/juice/runtime)

TypeDescriptionWhen You Need It
FlightManifestThe manifest generated by the Vite plugin at build time.Rarely. Only if you are building tooling around the manifest.
RouterOptionsConfiguration for createRouter().When you want to type-check your options object separately.
RedirectOptionsOptions for redirect(): currently extra headers.When wrapping redirect behavior in helpers that attach cookies or other headers.
ActionContext<TRoute>Second argument to server actions. Provides request, cookies, typed params, url.When your server action needs access to the request or route params.
ParsedBodyDiscriminated union: form | json | text.When you need to handle different content types in a single action.
ExtractRouteParams<T>Type-level extraction of route params from a pattern string.When building generic utilities that work with any route pattern.
PagePropsInterface augmented by juice-env.d.ts. Indexed by route pattern.Every route component. PageProps['/product/:id'] gives typed params.
JuiceMiddleware(req: Request, next: () => Promise<Response>) => Response | Promise<Response>When typing a middleware function explicitly.
ContextKey<T>Branded key carrying value type at compile time. Runtime: { name: string }.When defining typed context keys with createContextKey.
CacheAdapterStorage backend: get(key) and set(key, value, ttl?). Built in: memoryCache(), kvCache(kv).When writing your own adapter (Redis, D1, Deno KV) for cache(fn, { key }).
CacheOptionsCross-request options for cache(): key, revalidate, expire, tags.When sharing cache options between functions.
SSEEventEvent object accepted by eventStream(): data, optional event, id, and retry.When typing SSE generators or callback senders.
EventStreamOptionsOptions for eventStream(): extra headers and keepAlive.When customizing SSE headers or keep-alive behavior.
Channel / ChannelOptionsWhat createChannel() returns (subscribe, events, publish, subscribers) and its options (buffer, linger, broadcast).When passing a channel around or sharing its options.
ChannelSource / ChannelPublishThe (publish, key) => cleanup function a channel runs per key, and its publish parameter.When defining a source outside the createChannel() call.
BroadcastAdapterpublish(key, event) and subscribe(key, onEvent) returning an unsubscribe. Built in: memoryChannel(), redisChannel(client).When writing your own adapter (Postgres NOTIFY, Durable Objects, NATS).
RedisClientLike / RedisChannelOptionsThe client shape redisChannel() accepts (publish, subscribe, unsubscribe, duplicate, optional connect) and its prefix option.When wrapping a Redis client that isn't node-redis or Bun.redis.

@cmj/juice/node

createNodeHandler(manifest, options?)

Returns an http.createServer request listener for Node.js, the one runtime whose HTTP server does not accept a fetch handler. It builds the Request from req.url, the Host header and the raw headers, buffers the body up to maxBodySize (413 beyond it), aborts req.signal when the client disconnects, writes every Set-Cookie header, pipes the body, and serves /assets/* from the client build with immutable cache headers.

import { createServer } from 'node:http';
import { createNodeHandler } from '@cmj/juice/node';
import manifest from './flight-manifest.json';

createServer(
  createNodeHandler(manifest, {
    maxBodySize: 10 * 1024 * 1024, // default
    assets: 'dist/client',          // default; false to disable
    router: { root: import.meta.url },
  }),
).listen(3000);

// listener: (req: IncomingMessage, res: ServerResponse) => void

When to use: every Node.js deployment. Bun, Deno and Cloudflare Workers take the createRouter() handler directly. Router options go in options.router; its requestLimits.maxBodySize defaults to the adapter's maxBodySize. See Node.js.

Type Exports (@cmj/juice/node)

TypeDescriptionWhen You Need It
NodeHandlerOptionsOptions for createNodeHandler(): router, maxBodySize, assets.When building the options object separately or in a shared config.
NodeRequestListenerThe returned (req: IncomingMessage, res: ServerResponse) => void.When wrapping the listener (logging, WebSocket upgrades) with explicit types.

@cmj/juice/client

Link

Type-safe navigation component. Renders a standard <a> tag with SPA navigation via the Navigation API. Prefetches the destination segment on hover by default.

import { Link } from '@cmj/juice/client';

<Link href="/product/42">View Product</Link>
<Link href="/about" prefetch="viewport">About</Link>
<Link href="/login" replace>Log In</Link>
<Link href="/settings" prefetch="none">Settings</Link>

Props extend standard <a> attributes plus: prefetch('hover' | 'viewport' | 'none', default 'hover'), replace (replace history entry instead of push), scroll (set false to preserve scroll), and active-state styling props activeClassName / activeStyle.

useRouter()

Hook for programmatic navigation. Returns an object with pathname, push(), replace(), refresh(), prefetch(), back(), and forward(). refresh() re-renders the page segment in place; refresh('cart') refreshes the slices tagged cart.

'use client';
import { useRouter } from '@cmj/juice/client';

export function LogoutButton() {
  const router = useRouter();

  async function handleLogout() {
    await fetch('/api/logout', { method: 'POST' });
    router.push('/login');
  }

  return <button onClick={handleLogout}>Log out</button>;
}

initNavigation(setPage?, options?)

Configures segment navigation. The client bootstrap Juice generates already installs it on every page with a root layout; calling this from a client component only changes its options. Returns a cleanup function that removes the interceptor.

import { initNavigation } from '@cmj/juice/client';

const cleanup = initNavigation(null, {
  viewTransitions: true,
  prefetch: false,
});

// cleanup() removes the navigation interceptor

The first argument is ignored (earlier versions updated a page-level React root here) and kept for compatibility. Segment navigation intercepts same-origin navigations using the Navigation API, fetches the destination with the document's layout chain in X-Juice-Segment, and replaces the one <juice-segment> the server returns. Head tags the page hoists (title, meta, stylesheets) are synced into <head>.

If the Navigation API is not available (older browsers), navigation falls back to full page reloads. No polyfill is needed -- the app still works, just without SPA transitions.

NavigationOptions:

OptionTypeDefaultDescription
viewTransitionsbooleantrueUse the View Transitions API for smooth page transitions. Falls back to instant swap in browsers that do not support it.
prefetchbooleanfalseEnable hover/focus prefetching for all same-origin anchors globally. Leave this off if you want per-link control through Link prefetch.
callServerfunctionbuilt-inCustom server action RPC handler. Receives the action ID and arguments, returns the action result. See Server Actions for the default behavior.

When to use: only in custom client entry points. The scaffolded project sets this up for you. You touch this when you need to customize view transitions, override callServer, or intercept navigation events.

callServer (default behavior)

The built-in callServer handles server action RPC in the browser. When a server action is invoked, it:

  1. POSTs to the current URL with an x-juice-action-id header containing the action's ID.
  2. Sends the serialized arguments as the request body.
  3. Checks the response Content-Type:
  • text/x-component -- decodes via createFromFetch from react-server-dom-webpack/client. This triggers RSC reconciliation, which is why useOptimistic and useActionState work automatically.
  • application/json -- decodes via response.json(). For actions that return plain data without re-rendering.

You can replace this with a custom callServer in initNavigationoptions for custom headers, retry logic, or error reporting.

prefetchRSC(url)

Manually prefetches the RSC payload for a URL. The payload is cached for 30 seconds, and subsequent calls with the same URL within that window are idempotent (no duplicate fetches). When the user navigates to a prefetched URL, the cached payload is used immediately -- no network request.

import { prefetchRSC } from '@cmj/juice/client';

// Prefetch the next page when the user starts typing
function SearchInput() {
  function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    const query = e.target.value;
    if (query.length > 2) {
      prefetchRSC(`/search?q=${encodeURIComponent(query)}`);
    }
  }

  return <input onChange={handleChange} placeholder="Search..." />;
}

// Prefetch a known destination ahead of time
prefetchRSC('/onboarding/step-2');

// Calling again within 30s is a no-op
prefetchRSC('/onboarding/step-2'); // idempotent

When to use: when you know the user is likely to navigate somewhere but there is no Link element to attach prefetching to. Examples: search results, keyboard navigation, wizard flows, post-login redirects.

Client Type Exports

TypeDescription
LinkPropsProps for the Link component. Extends standard anchor attributes plus prefetch, replace, scroll, and active-state styling props.
PrefetchStrategy'hover' | 'viewport' | 'none'
NavigationOptionsOptions for initNavigation(): viewTransitions, prefetch, and callServer.
RouterReturn type of useRouter(): pathname, push(), replace(), refresh(), prefetch(), back(), forward().

When NOT to Use These APIs

If you are building a page with no navigation (a single dashboard, an embedded widget), you do not need Link, useRouter, or initNavigation. These are SPA navigation primitives. Without multiple pages to navigate between, they add unused code to your client bundle.