Data Fetching
In Next.js pages router, you had getServerSideProps. In Remix, you had loaders. In Juice, your component is async. You just fetch.
The Paradigm Shift
React Server Components are async. This means you can awaitdirectly in the component body. No special data-fetching function, no loader convention, no intermediate serialization layer. The component IS the data fetcher.
// app/routes/blog/[slug].tsx
import type { PageProps } from '@cmj/juice/runtime';
export default async function BlogPost(props: PageProps['/blog/:slug']) {
const post = await db.posts.findBySlug(props.params.slug);
if (!post) {
throw new Response('Not Found', { status: 404 });
}
return (
<article>
<h1>{post.title}</h1>
<time dateTime={post.publishedAt}>{post.publishedAt}</time>
<div>{post.body}</div>
</article>
);
}Notice the error handling. When the post does not exist, you throw a Responsewith status 404. The Juice runtime catches this and returns it as the HTTP response. This works in any server component, at any depth in the tree.
What happens when the API is down? If db.posts.findBySlug()throws an error, Juice catches it via the onError handler (or the nearest catch.tsx boundary if streaming is enabled). In production, the user sees a generic error page. In development, they see a stack trace. You should handle expected failures (not found, unauthorized) explicitly. Let unexpected failures (network errors, database timeouts) propagate to the error boundary.
Request-Scoped cache()
Here is the problem cache() solves. You have a getUser()function. Your page component calls it. Your sidebar component calls it. Your header component calls it. Without deduplication, that is three database queries for the same user in a single request.
import { cache } from '@cmj/juice/runtime';
const getUser = cache(async (userId: string) => {
console.log('Fetching user', userId); // Logged once per request
return await db.users.find(userId);
});
// Page component
export default async function Profile({ params }: { params: { id: string } }) {
const user = await getUser(params.id);
return (
<div>
<UserHeader userId={params.id} />
<h1>{user.name}</h1>
<UserSidebar userId={params.id} />
</div>
);
}
// Called in the same request -- deduplicated, no second DB query
async function UserHeader({ userId }: { userId: string }) {
const user = await getUser(userId);
return <header>{user.name} ({user.email})</header>;
}
async function UserSidebar({ userId }: { userId: string }) {
const user = await getUser(userId);
return <aside>Member since {user.createdAt}</aside>;
}How Identity-Based Keys Work
Coming from Next.js: Next.js extends fetch() with automatic deduplication based on URL strings. Juice does not patch fetch(). Instead, cache() wraps any function and deduplicates based on argument identity.
Primitives (strings, numbers, booleans) are compared by value: getUser("42")called twice returns the same promise. Objects and functions are compared by reference using a WeakMap of monotonic IDs. This means passing a Requestobject works correctly -- two calls with the same Request instance deduplicate, but two different Request objects with identical URLs do not. This is deliberate. JSON serialization of complex objects is fragile (circular references, non-serializable values, key ordering). Reference identity is always correct.
When NOT to Use cache()
cache() is for reads. If your function has side effects (writes to the database, sends an email, logs an audit event), do not cache it. Cached functions are memoized: the side effect would only happen on the first call, and subsequent calls would silently return the cached result without executing the function body.
Cross-Request Caching
Plain cache(fn) is per-request. Give it a key and results are shared across requests too, stored through the router's cache adapter.
import { cache } from '@cmj/juice/runtime';
export const getProduct = cache(
async (id: string) => db.products.find(id),
{
key: 'product', // unique name; also an implicit tag
revalidate: 60, // stale after 60s
tags: (id) => [`product:${id}`], // for revalidateTag()
},
);Stale-while-revalidate. Once an entry is older than revalidate seconds, the next call still returns it immediately and computes a fresh value in the background. With revalidate: false (the default), entries are kept until a tag is revalidated. Add expire to have the adapter drop entries entirely after that many seconds.
Invalidation. After a write, call revalidateTag(). The next call waits for fresh data instead of serving the old value.
'use server';
import { revalidateTag } from '@cmj/juice/runtime';
export async function updatePrice(id: string, price: number) {
await db.products.update(id, { price });
await revalidateTag(`product:${id}`); // or revalidateTag('product') for all
}The same call updates the screen: the action's response names the tags it revalidated and the client re-fetches every <Slice> tagged with them. See Partial Rendering.
Keys come from arguments. Arguments must be plain data (strings, numbers, dates, arrays, plain objects). Pass an ID, not a Request or a database client. Results must be serializable by the adapter: anything structuredClone can copy for memoryCache(), JSON for kvCache().
Storage. By default entries live in a per-process LRU (memoryCache()). On Cloudflare Workers, use KV so every isolate shares them. Background refreshes and writes are handed to ctx.waitUntil automatically. KV is eventually consistent, so an invalidation can take up to a minute to reach other locations.
import { createRouter, kvCache } from '@cmj/juice/runtime';
let handler: ReturnType<typeof createRouter> | undefined;
export default {
fetch(req: Request, env: Env, ctx: ExecutionContext) {
handler ??= createRouter(manifest, { cache: kvCache(env.CACHE) });
return handler(req, env, ctx);
},
};To cache whole HTML responses at the CDN instead, set response.cache:
export const response = {
cache: 'public, s-maxage=60, stale-while-revalidate=300',
};Response Headers for Caching
Cache-Control headers are the platform's caching mechanism. Juice does not own caching. It sets headers on the Response, and the CDN (Cloudflare, Vercel, Fastly) decides what to cache. This is intentional: Juice does not reinvent HTTP caching.
export const response = {
headers: {
'Cache-Control': 'public, max-age=3600, s-maxage=86400',
},
};max-age controls the browser cache. s-maxage controls the CDN cache. Set s-maxage higher than max-age so the CDN serves stale content while the browser re-validates. This is standard HTTP, not a Juice feature.
Metadata and SEO
React 19 hoists <title> and <meta> elements from anywhere in the tree into <head>. Juice generates them from your response config.
Static metadata:
export const response = {
head: {
title: 'About Us',
description: 'Learn about our team and mission.',
'og:image': '/images/about-og.png',
},
};Dynamic metadata from params:
export async function response({ params }) {
const product = await getProduct(params.id);
return {
head: {
title: product.name,
description: product.summary,
'og:image': product.imageUrl,
'twitter:card': 'summary_large_image',
},
};
}Response headers and caching:
export const response = {
head: { title: 'Products' },
cache: 'public, s-maxage=60, stale-while-revalidate=300',
};The response function receives { params, searchParams, request }. Use it when you need request headers (e.g. for auth-dependent metadata).
Cache Control
Use response.cache to control caching. Set it to 'immutable' for static pages, a custom Cache-Control string for fine-grained control, or false for no-store.
export const response = {
cache: 'immutable',
};
export default function About() {
return <h1>About Us</h1>;
}When NOT to Use Juice for Data Fetching
If your app is 90% client-side state (a spreadsheet, a drawing tool, a chat app), server components add round-trip latency for every data update. You would be better served by 'use client' on the entire page with client-side data fetching (React Query, SWR, or plain fetch in useEffect). Juice still works as the shell renderer, but the server component model is not helping you.