Skip to content

Router Options

All configuration options for createRouter(manifest, options?). Every field is optional. The router works with zero configuration for development, but production deployments typically set at least root and streaming.

RouterOptions

OptionTypeDefaultWhat It Does
rootstring--Base URL for resolving module import() paths. Without this, modules resolve relative to the Juice package, not your app.
basePathstring'/'URL prefix for all routes. Use when your app lives at a subpath (e.g., '/docs').
streamingboolean | 'shell'falseHTML streaming mode. false = wait for full render. 'shell' = stream after shell. true = stream immediately.
noncestring | (req) => string | Promise<string>--CSP nonce added to all inline scripts. Use a function to generate a fresh nonce per request.
rscbooleanfalseDeprecated and ignored (a dev-mode warning says so). Client navigation fetches HTML segments via the X-Juice-Segment header; no React Flight payload is served, and Accept: text/x-component requests get 406.
csrfProtectionboolean | { allowedOrigins?: string[] }trueCSRF validation on POST requests. Pass false for public APIs or webhooks.
mode'development' | 'production''production'Controls error verbosity (stack traces in dev, generic errors in prod), module caching, and HMR injection.
cacheCacheAdaptermemoryCache()Storage for cross-request cache(fn, { key }) results and revalidateTag() timestamps. Built in: memoryCache() and kvCache(kv).
requestTimeoutnumberundefinedMax request time in milliseconds. Exceeding returns 504 and aborts request.signal / ctx.signal.
requestLimitsRequestLimits--Byte limits for request bodies: maxBodySize, maxJsonSize, maxFormSize, maxTextSize, and maxFileSize.
assetPrefixstring'/'Public URL prefix for client chunk paths. Use when assets are served from a CDN on a different domain.
clientEntrystring--Path to the client entry module that calls hydrateRoot(). Only needed for custom client entry points.
hmrUrlstring'/@vite/client'Vite HMR WebSocket URL. Only relevant in development mode.
onBeforeRequest(req: Request) => Response | void--Hook called before routing. Return a Response to short-circuit (maintenance mode, health checks).
onNotFound(req: Request) => Response404 textHook called when no route matches. Return a custom 404 page.
onError(error: unknown, req: Request) => Response500 textHook for unhandled errors. Thrown Response objects (redirects, 404s) never reach this hook.

NavigationOptions (@cmj/juice/client)

Options for initNavigation(setPage?, options?). These control how segment navigation behaves after the initial HTML page load. The client bootstrap installs navigation with the defaults; turn it off entirely with juice({ navigation: false }) in vite.config.ts.

OptionTypeDefaultDescription
viewTransitionsbooleantrueUse the View Transitions API for smooth page transitions. When true, page swaps are wrapped in document.startViewTransition(). Falls back to instant swap in browsers that do not support the API.
prefetchbooleanfalseEnable hover/focus prefetching for all same-origin anchors globally. When you need per-link control, leave this false and use each Link component's prefetch prop.
callServer(actionId: string, args: unknown[]) => Promise<unknown>—Deprecated and ignored. Server actions called from the browser POST to the current URL with x-juice-action-id and resolve with the action's JSON result (or follow its redirect).

Real Examples

Production Deployment (Cloudflare Workers)

createRouter(manifest, {
  root: import.meta.url,
  streaming: 'shell',
  nonce: () => crypto.randomUUID(),
  requestTimeout: 15_000,
  requestLimits: {
    maxBodySize: 10 * 1024 * 1024,
    maxJsonSize: 1 * 1024 * 1024,
    maxFileSize: 5 * 1024 * 1024,
  },
  csrfProtection: {
    allowedOrigins: ['https://admin.example.com'],
  },
});

Why these options: root is required for production module resolution. streaming: 'shell' gives fast TTFB with correct status codes for the shell. nonce makes inline scripts CSP-compliant. The timeout and body limits cap slow or oversized requests. CSRF allows an additional admin origin. Note: rsc is not set because RSC negotiation is automatic.

Public API (No CSRF, Custom Errors)

createRouter(manifest, {
  root: import.meta.url,
  csrfProtection: false,
  requestTimeout: 30_000,
  requestLimits: {
    maxBodySize: 2 * 1024 * 1024,
    maxJsonSize: 512 * 1024,
  },
  onError: (error, req) => {
    console.error('[api]', req.url, error);
    return Response.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  },
  onNotFound: (req) => {
    return Response.json(
      { error: 'Not found', path: new URL(req.url).pathname },
      { status: 404 }
    );
  },
});

Why these options: CSRF is disabled because this is a public API that uses bearer tokens, not cookies. requestTimeout prevents slow queries from hanging indefinitely. requestLimits rejects oversized JSON before route handlers do expensive work. Custom error handlers return JSON instead of HTML.

Maintenance Mode

createRouter(manifest, {
  root: import.meta.url,
  onBeforeRequest: (req) => {
    if (process.env.MAINTENANCE === 'true') {
      return new Response('We are performing scheduled maintenance. Back soon.', {
        status: 503,
        headers: { 'Retry-After': '3600' },
      });
    }
  },
});

CDN Asset Prefix

createRouter(manifest, {
  root: import.meta.url,
  assetPrefix: 'https://cdn.example.com/assets/',
});

When to use: when your static assets (JS chunks, CSS) are served from a different domain than your server. The runtime uses this prefix when generating <script> and <link> tags.

Subpath Deployment

// App lives at example.com/docs/
createRouter(manifest, {
  root: import.meta.url,
  basePath: '/docs',
});

When to use: when your app is mounted at a URL subpath behind a reverse proxy. All route patterns are prefixed with the base path.

CacheAdapter Interface

interface CacheAdapter {
  get(key: string): unknown | Promise<unknown>;
  set(key: string, value: unknown, ttl?: number): void | Promise<void>;
}

The router stores cache(fn, { key }) entries and revalidateTag() timestamps through this adapter. Values are plain data, so adapters that serialize (KV, Redis) can use JSON. Without one, a per-process memoryCache() is used.

import { createRouter, memoryCache, kvCache } from '@cmj/juice/runtime';

// Per-process LRU (the default)
createRouter(manifest, { cache: memoryCache({ maxEntries: 5000 }) });

// Cloudflare Workers KV
createRouter(manifest, { cache: kvCache(env.CACHE, { prefix: 'v1:' }) });

// Anything else: Redis, D1, Deno KV...
createRouter(manifest, {
  cache: {
    get: async (key) => JSON.parse((await redis.get(key)) ?? 'null') ?? undefined,
    set: (key, value, ttl) => redis.set(key, JSON.stringify(value), ...(ttl ? ['EX', ttl] : [])),
  },
});

When NOT to Configure

The zero-config default (createRouter(manifest)) works for development. Do not add options you do not understand. Common mistakes:

  • Setting streaming: true without understanding that status codes are always 200. Use 'shell' if you want streaming with correct status codes.
  • Setting rsc: true thinking it is required for SPA navigation. It is not -- RSC negotiation is automatic via the Accept header. This option has no effect.
  • Setting requestTimeout too low. If your data fetching takes 2 seconds, a 1-second timeout kills every request. Start without a timeout and add one when you know your P99 latency.
  • Disabling CSRF on a cookie-based app. If your app uses cookies for auth, CSRF protection is essential. Only disable it for token-based APIs.