Server rendering
A server has no workers. It reads with an in-process client (mode: 'in-process', no workerUrl), which runs the engine and imports the fetcher module in the server's own process. The engine has no DOM or worker code at module top level, so it loads in Node and Bun.
The page then carries the server's answer twice:
- the columns, so the browser's hydration render shows what the server rendered, before any client exists;
- a snapshot, which the browser applies to its own cache with
hydrate, so its first live read fetches only what the server did not know, typically the provisional tail.
/ssr). The server has rendered the page before, so its in-process cache already holds the history; it renders the page from it, the browser's cache starts from the server's snapshot, and the chart draws the history at once. The backend serves only the newest bars, to the server's read and to the browser's. A server's first render after it starts fetches the history once. Recorded headless with Playwright from the demo hub's vanilla reference client; the counters above the page are its mock backend's.The server
import {
type CacheConfig,
createClient,
encodeSnapshot,
type Range,
} from "@anishbenji/tscache";
import type { Context } from "./fetcher";
export const candles: CacheConfig = {
id: "crypto/BTC",
interval: 60_000,
fields: { open: "f64", high: "f64", low: "f64", close: "f64", volume: "u32" },
};
export interface ServerOptions {
/** The fetcher module as a URL the server can import(). */
fetcherModule: string;
/** The backend's origin: a server has no page origin to resolve against. */
origin: string;
}
/**
* The page renderer of this server process. Create it once at startup: it
* owns the process's one client, so a render reads what earlier renders
* fetched. Every visitor reads the same cache: public data only.
*/
export async function createRenderer({ fetcherModule, origin }: ServerOptions) {
const context: Context = { origin };
const client = await createClient({
mode: "in-process", // a server has no workers
fetcher: { module: fetcherModule, context },
});
const cache = await client.cache(candles);
return async (range: Range): Promise<string> => {
// One read gives the page's columns and the cache's snapshot.
const { snapshot, ...result } = await cache.get(range, { snapshot: true });
if (snapshot === undefined) throw new Error("the read carries no snapshot");
// Escape every "<" so no string can close the script element.
const json = JSON.stringify(encodeSnapshot(snapshot)).replaceAll(
"<",
"\\u003c",
);
return `<p id="chart">${result.timestamps.length} candles</p>
<script id="tscache-snapshot" type="application/json">${json}</script>`;
};
}Escape every < before the JSON goes into the page
JSON.stringify leaves < as it is, and the HTML parser ends a <script> element at the first </script> it meets, inside a JSON string or not. A field name, a dataset version, or anything else in the element (the columns beside the snapshot) that contains </script> would end the element early: the rest of the JSON is parsed as HTML, the browser's JSON.parse of the element's text throws, and when the string comes from data, the text after it runs as markup and script in your page (cross-site scripting). Replacing every < with \u003c, as the snippet does, keeps the JSON valid and decoding to the same value, and leaves the parser nothing to end the element with. tscache does not do it for you: encodeSnapshot returns a JSON value, not HTML.
- One client per server process, created at startup and shared by every render, so a render reads what earlier renders fetched. Every visitor then reads the same cache: use it for public data only.
- The server must be little-endian, as snapshot field bytes are: on a big-endian host (s390x, for example)
encodeSnapshotanddecodeSnapshotthrowTscacheError. - The fetcher URL must be one the server can
import(). With Vite,?fetchergives server code a file URL in a build and a path the module runner resolves in dev (The Vite plugin). - A server has no page origin, so a fetcher that requests relative paths needs the backend's origin from its context, as the server half above passes it. This site's fetcher and the examples' read
context.originand resolve each request URL against it; the browser's client omits it. - The server's own credential, if the backend needs one, goes in the server client's context, never a visitor's.
The browser
import {
type ClientOptions,
createClient,
decodeSnapshot,
type EncodedSnapshot,
type GetResult,
type Range,
TscacheError,
} from "@anishbenji/tscache";
import { candles } from "./snapshots-server";
/**
* Starts the page's cache from the server's snapshot (the JSON text of its
* script element), then reads `range`, which fetches only what the
* snapshot did not cover. `options` carry the worker URL and the fetcher:
* the browser's client loads what the snapshot lacks.
*/
export async function startCache(
options: ClientOptions,
range: Range,
text: string | null | undefined,
): Promise<GetResult> {
const client = await createClient(options);
// A worker lost meanwhile fails every pending call, hydrate included, as
// does a page hidden for good: pagehide disposes the client.
let lost = false;
client.on("workerLost", () => {
lost = true;
});
const cache = await client.cache(candles);
if (text != null) {
try {
const seed = decodeSnapshot(JSON.parse(text) as EncodedSnapshot);
const { applied, skipped } = await cache.hydrate(seed);
console.log(applied, skipped); // skipped: "version-mismatch" when refused
} catch (error) {
// The client is gone: no read follows, so the loss is the answer.
if (lost || disposed(error)) throw error;
// Not seeded: hydration saves fetches and is never needed for correct
// answers, so the read below fetches instead. A worker from before
// hydrate (a stale cached script) refuses the op; any other failure
// is worth a warning in development. It names the error and never
// prints its message, which can quote the snapshot: the page's data.
const old =
error instanceof TscacheError && error.message === "unknown op hydrate";
if (!old && development()) {
const why = error instanceof Error ? error.name : typeof error;
console.warn(`snapshot not applied (${why}); the cache fetches`);
}
}
}
return cache.get(range);
}
/** Whether `error` is a disposed client's answer to every call. */
function disposed(error: unknown): boolean {
return error instanceof TscacheError && error.message === "client disposed";
}
// Bundlers replace the exact text `process.env.NODE_ENV` at build time, so
// it is read bare; a page that no bundler prepared has no `process`.
declare const process: { env: { NODE_ENV?: string } };
/** Whether this is a development build. */
function development(): boolean {
try {
return process.env.NODE_ENV !== "production";
} catch {
return false;
}
}import workerUrl from "@anishbenji/tscache/worker?worker&url";
import fetcherModule from "./fetcher.ts?fetcher";
import { startCache } from "./snapshots-browser";
const MINUTE = 60_000;
const now = Math.floor(Date.now() / MINUTE) * MINUTE;
const result = await startCache(
{ workerUrl, fetcher: { module: fetcherModule } },
{ start: now - 6 * 60 * MINUTE, end: now }, // the range the server read
document.getElementById("tscache-snapshot")?.textContent,
);Apply the snapshot before the first live read. hydrate writes only where the browser's cache neither covers anything nor holds a provisional point, in one call inside the worker, so another tab's newer fetch is never replaced. A snapshot of another dataset version is refused (skipped: 'version-mismatch'), and a worker from before hydrate rejects it with "unknown op hydrate": treat both as nothing applied, and the cache fetches. Any other failure to apply it, a malformed snapshot for example, counts as not seeded too: the snippet warns in development with the error's name only, never its message, which can quote the snapshot, and the snapshot carries the page's data. Snapshots has the rules.
The snapshot stays usable after hydrate, so the client that replaces a lost one can be seeded from it too; the integrations' connect(open, seeds) does that.
Calendar caches
A cache with a calendar interval in a zone computes its slot starts from the runtime's time-zone data, and the server and the browser each use their own. A snapshot of such a cache therefore stores, beside each instant that names a slot (its range, its coverage ranges, the start of each block of points), the slot the server gave it. hydrate refuses a snapshot when the browser's data places one of those instants in another slot, with a TscacheError, and changes nothing; treat that as "not seeded" and let the cache fetch.
- Keep the server's zone data current (Node's ICU data, which a Node upgrade brings). The usual cause of a difference is a rule change one side does not have yet.
- What the check covers. A snapshot that applies has every bar on the day, week or month the server put it on. It does not compare every bar's instant: when the two sides disagree only about dates strictly inside the snapshot, for example a daylight-saving rule one side lacks while both ends of the snapshot fall in the season where they agree, the snapshot applies, and the browser shows those bars at its own start of their slots, as it would after fetching them itself.
- Very fragmented snapshots are refused. The check's work is bounded before it starts: a snapshot with more than about 14,500 separate coverage ranges is refused. A snapshot of bars has one coverage range per uninterrupted stretch.
encodeSnapshot and decodeSnapshot carry a calendar cache's snapshot as they carry any other.
How stale can a snapshot be?
As old as the page. With a versioned dataset, a stale snapshot is refused, or, in a cache created without a version, adopted until the first response reporting a newer version clears it. Without a version, a seed is no staler than the server's render was.
Complete versions
integrations/shared/server.tsandhydration.ts: the server reader and the page encoding every framework snippet uses; Vanilla JavaScript, React and Solid show each framework's halves.examples/react-ssrandexamples/solid-ssr: runnable server-rendered apps.- The reference clients'
/ssrpages (reference/).