Skip to content

Partial Rendering

Juice never has to render the whole page again. Navigation re-renders only the layouts that changed (segments), and regions that change on their own are routes embedded in the page (slices). Both are plain HTML over a plain GET, so middleware, caching and thrown responses keep working.

The Unit Is the Route

A Juice route is a layout chain around a page. Each layout's children are wrapped in a <juice-segment data-depth> marker; the page sits at the deepest one. Everything partial in Juice is expressed with this one idea: ask the server for a route, and tell it how much of it you already have.

<html>                                  root layout
  <nav>…islands keep their state…</nav>
  <juice-segment data-depth="1">        ← swapped when the section changes
    <section>                           admin layout
      <juice-segment data-depth="2">    ← swapped when only the page changes
        <h1>Users</h1>
      </juice-segment>
    </section>
  </juice-segment>
</html>

Segments: Navigation

On a same-origin navigation the client sends the layout chain it holds in X-Juice-Segment. The server renders from the first layout that differs and answers with that one <juice-segment> and its depth in X-Juice-Segment-Depth. The client swaps that element, moves hoisted <title>, <meta> and stylesheet links into <head>, and leaves everything above it alone — including the state of client components there. Anything the server cannot answer as a segment (no shared root layout, a thrown Response, a 404) becomes an ordinary document load.

This is on for every app with a root layout and needs no configuration. Set juice({ navigation: false }) in vite.config.ts to keep every link a document load.

Slices: Server Islands

A slice is a route file that another page embeds. It is discovered, typed, guarded by middleware and cached like every other route, and GET-ting its URL renders it as a page too.

// app/routes/dashboard/cart.tsx — a route, and therefore a slice
import { cache } from '@cmj/juice/runtime';
import type { PageProps } from '@cmj/juice/runtime';

const cartItems = cache(getCartItems, { key: 'cart', tags: (userId) => [`cart:${userId}`] });

export default async function Cart({ request }: PageProps['/dashboard/cart']) {
  const user = await currentUser(request);   // identity from the request, not props
  const items = await cartItems(user.id);
  return <ul>{items.map((i) => <li key={i.id}>{i.name}</li>)}</ul>;
}

export const response = { embed: 'only' };    // optional: not a page of its own
// app/routes/dashboard.tsx — embeds it
import { Slice } from '@cmj/juice/runtime';

export default function Dashboard() {
  return (
    <main>
      <h1>Dashboard</h1>
      <Slice href="/dashboard/cart" tags={['cart']} />
      <Slice href="/widgets/weather?city=lon" defer fallback={<p>Loading…</p>} />
    </main>
  );
}

First render: in the tree

On the page request the slice renders inside the page's React tree — one stream, one set of stylesheets, Suspense works — as the slice route's page component with its pending.tsx and catch.tsx boundaries, and without its layouts or head metadata. The slice gets its own Request (the page's headers and signal, its own URL, the same context) and runs the middleware of its route that the page's chain did not already run. A middleware that answers instead of calling next() leaves the slice empty; in dev the terminal says why.

Refresh: after a server action

When an action calls revalidateTag('cart:42'), its response carries X-Juice-Revalidated: cart%3A42. The client re-fetches every slice whose tags match — a slice tagged cart matches cart and cart:* — before the action's promise resolves, so a pending state covers the update. Action authors write nothing new.

'use server';
import { revalidateTag } from '@cmj/juice/runtime';

export async function addToCart(formData: FormData, { request }: ActionContext) {
  const user = await currentUser(request);
  await db.cart.add(user.id, formData.get('sku'));
  await revalidateTag(`cart:${user.id}`);   // invalidates the cache AND refreshes the cart slice
}

An action that revalidates nothing refreshes the slice its form sits in, the way a Turbo frame does. Say <Slice refresh="manual"> to opt a slice out.

Forms with and without JavaScript

A <form action={serverAction}> rendered by a server component is a real POST form. Without JavaScript the browser posts it and the server answers with a 303 back to the page, which re-renders with the action's effects. With JavaScript, the bootstrap posts the same form with fetch() and refreshes what the action changed: the tagged slices, the enclosing slice, or the page segment. Forms inside client components are handled by React and get the same refresh.

Deferred slices

defer renders only the fallback on the server (the prop, or the route's pending.tsx) and the browser fetches the slice once the page has loaded; defer="visible" waits until it scrolls into view. This is the island architecture's lazy server render: heavy or personalised regions leave the critical path, and because the fetch is a plain GET to a real URL, the browser cache and CDNs can serve it.

Programmatic refresh

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

const router = useRouter();
await router.refresh();        // re-fetch the page segment and swap it in place
await router.refresh('cart');  // refresh the slices tagged cart

Trust model

A slice's href is a URL the client chose, exactly like a page URL. Params and search params are untrusted input; identity comes from request. This is why slices carry no props: there is nothing to serialise, sign or trust. Unknown, cross-origin and self-embedding hrefs throw with an explanation.

What Survives a Swap

Segments and slices are not replaced wholesale: the new markup is morphed into the live DOM. Elements that still exist (same tag, same id, same island) are kept and updated, so:

  • focus, selection and scroll positions stay where they were;
  • an input you have edited keeps your value; untouched inputs take the server's;
  • a hydrated client component keeps its state and receives its new props, like a re-render; a component that disappeared is unmounted, a new one hydrates.

Give list items and other repeated elements an id and they are matched even when they move.

Streaming

With streaming set on the router, segments and slices stream like documents: the shell arrives first with Suspense fallbacks in place, and each boundary fills in when its data resolves. The client applies React's completions itself, since no HTML parser runs the inline scripts of a fragment. Thrown responses in the shell still set the status.

Styling the In-Between

A refreshing slice keeps its content and sets aria-busy="true" until the new content arrives; a form being posted does the same. Deferred slices show their fallback.

juice-slice[aria-busy="true"] { opacity: 0.6; transition: opacity 150ms; }

Protocol

RequestResponseBody
GET /routeVary: X-Juice-SegmentThe document, with <juice-segment> and <juice-slice> markers
X-Juice-Segment: <layout ids>X-Juice-Segment-Depth: kHoisted head tags, then the <juice-segment data-depth="k"> to replace (0: the whole document)
X-Juice-Segment: sliceX-Juice-Slice: 1The route without layouts: a slice's content
POST (server action)X-Juice-Revalidated: tag,tagThe action's result; 303 to the page for a browser form post

Troubleshooting

SymptomLikely causeFix
A slice never refreshes after an actionThe action revalidated no tag that matches the slice, and the form is not inside itCall revalidateTag() with a tag the slice lists, or put the form in the slice
Deferred slices stay on their fallbackThe client bootstrap is not loadedCheck the page loads juice-client-*.js (or /@juice/dev-client in dev) without errors
500 mentioning "matches no route"The href is not a route (typo, or basePath missing)Use the route's URL as the browser would request it
A slice renders emptyIts middleware answered instead of calling next()Read the dev warning; share auth through context set by the page's middleware
The slice's title replaced the page titleIt cannot: slices render without head metadataSet the title in the page's response.head