A simple stateless (as opposed to synced) React API for Rindle. Built on the standard Rindle architecture, with a small convention on top: components ask for queries by name, and the hooks subscribe and unsubscribe as components mount and unmount.
Overview
- Components call
useQuery(name, args). The page never sends raw queries. - The hooks batch every add and remove made in one tick into one
POSTto a subscribe route that your server is expected to provide. - The subscribe route checks the user, maps each name and its args to SQL, and forwards the
batch to Rindle with
subscribeOps. - The hooks get a stream token from an auth route your server provides, which gets it from Rindle. They open their stream straight from Rindle with it, and send later stream tokens up the stream to keep it open, as in Architecture.
Server Routes
Add both routes under one base path. They use @rindle/api.
The hooks post JSON with no Content-Type header, so read the body with request.json(), not by
its content type. That makes each call a simple request: routes on another origin than the page
need only answer with Access-Control-Allow-Origin, and the browser sends no preflight first.
// POST /api/rindle/auth
export async function POST(request: Request) {
const user = await getUser(request); // your own auth
const { clientID, streamToken } = await request.json();
const result = await db.authorizeStream({
clientID,
userID: user?.id,
streamToken,
});
return Response.json(result);
}// POST /api/rindle/subscribe
export async function POST(request: Request) {
const user = await getUser(request);
const { clientID, streamToken, ops } = await request.json();
const results = await db.subscribeOps({
clientID,
userID: user?.id,
streamToken,
ops: ops.map((op) =>
op.op === "remove"
? op
: { ...op, ...queryFor(user, op.name, op.args) },
),
});
return Response.json(results);
}
// Yours: maps a query name and its args to SQL for this user.
function queryFor(user, name, args) {
if (name === "notes") {
return {
sql: "SELECT id, title FROM note WHERE owner_id = ? ORDER BY id",
params: [user.id],
};
}
throw new Error(`unknown query: ${name}`);
}authreceives{ clientID, streamToken }and returns{ streamToken }. The page calls it when it opens its stream, as the client is created, and every few minutes to keep the stream open.streamTokenis the page’s previous stream token, once it has one. With server rendering, the page arrives with its first stream token and skips that first call.subscribereceives{ clientID, streamToken, ops }. Each op is{ op: "add", id, name, args }or{ op: "remove", id }, andstreamTokenis the page’s latest stream token. Return the results unchanged: one per op, in order.
Client
createClient
import { createClient } from "@rindle/react";
const db = createClient({
base: "/api/rindle",
stream: "https://rindle.example.com",
});The page’s client. Create it once per page load. It opens its stream when you create it, before
any query, and keeps it open until close(), so a query waits only for its own add. It looks after
the stream: it keeps it open with fresh stream tokens, reconnects when it drops, and if Rindle
loses the page’s queries, sends them all again.
| Option | |
|---|---|
base |
Where your server routes live: ${base}/auth and ${base}/subscribe. |
stream |
Rindle’s public address. The page opens its stream there. |
headers |
Sent with every request to your routes. An object, or a function that returns one. |
credentials |
Default "same-origin". |
fetch |
A custom fetch, for requests to your routes. |
hydrate |
true to pick up queries from a server-rendered page. See Server Rendering. |
db.close() closes the stream.
RindleProvider
import { RindleProvider } from "@rindle/react";
<RindleProvider client={db}>
<App />
</RindleProvider>Makes db available to useQuery below it. In the browser, pass the client created once for
the page. On the server, each request has its own; see Server Rendering.
Hooks
useQuery
import { useQuery } from "@rindle/react";
const { rows, status, error } = useQuery<Note>("notes", { folder });Keeps a component rendering a live query. Re-renders when the rows change, and stops the query on unmount.
name and args go to your subscribe route, which maps them to SQL.
Returns:
rows |
The current rows. Empty until they arrive. |
status |
"loading", "complete" or "error". |
error |
An Error, when status is "error". If your route or Rindle refused the query, a LiveQueryError with its HTTP status and its code (forbidden, compile, …). |
Every add and remove made in one tick goes out as one request to your subscribe route.
Passing null for the name runs nothing and returns status: "loading".
Use it to wait on an argument.
Changing the name or args stops the old query and starts the new one. Args are compared by value,
so an inline object or array is fine. Until the new query is complete, rows are the old
query’s rows and status is "loading", so a change doesn’t flash empty. Pass
{ keepPrevious: false } to get empty rows instead.
On the server, inside a provider given an SSR client, the hook suspends until the rows arrive. That needs React 19.
Mutations
Write data however you like. This library isn’t involved: call your own endpoint, which checks the user and writes to Rindle as in Writes. Every query the write affects updates on its own, and the change reaches each page on its stream.
Server Rendering
Components use the same useQuery hook on the server and in the browser. The server runs
your queries, renders the rows, and puts them in the page. The browser shows the page, then keeps
the same queries live. It doesn’t ask your subscribe route for them again.
Server-rendered pages hold one user’s data. Serve them with Cache-Control: private, no-store
so a CDN never shares them.
How It Works
- The server render is a client. It opens a stream to Rindle and adds the page’s queries as
the signed-in user. It maps each name to SQL with the same
queryForyour subscribe route calls, in-process, and sends the batch withdb.subscribeOps, as the route does for the browser. - Hooks wait for their rows.
useQuerysuspends on the server until its query’s rows arrive, then renders them. - The page carries the queries. Along with the HTML, the page includes each query’s data,
the ID of the client that holds them, and a stream token for that client from
db.authorizeStream. The browser needs no round trip to your auth route before it starts. - The browser takes over. It builds its views from the page, so hydration matches the server’s HTML. It opens its stream straight from Rindle with the page’s stream token, as the same client. Changes continue from where the server stopped.
If the browser takes too long to take over, Rindle drops the server’s queries. The browser then asks your subscribe route for them as usual, and keeps showing the server’s rows until fresh ones arrive.
Wiring It Up
SSR builds on your server routes. They don’t change. The server render reads its stream from Rindle with the API token, and the browser reads its own straight from Rindle.
Components
Components get their client from RindleProvider, as in the browser:
import { useQuery } from "@rindle/react";
type Note = { id: number; title: string };
export function Notes() {
const { rows, status, error } = useQuery<Note>("notes");
if (error) return <p>Couldn't load notes: {error.message}</p>;
if (status === "loading") return <p>Loading…</p>;
return <ul>{rows.map((n) => <li key={n.id}>{n.title}</li>)}</ul>;
}The server renders many users’ pages at once, so each request gets its own client. The provider is how a component finds it.
The Server Entry
Create an SSR client for the request, render, then add its script to the page:
import { createSSRClient } from "@rindle/react/server";
import { RindleProvider } from "@rindle/react";
import { renderToReadableStream } from "react-dom/server";
import { db as rindle } from "./lib/rindle"; // your @rindle/api client
// What your subscribe route calls
import { queryFor } from "./lib/queries";
export async function renderPage(request: Request): Promise<Response> {
const user = await getUser(request); // your auth
const db = createSSRClient({
rindle,
queries: (name, args) => queryFor(user, name, args),
userID: user?.id,
});
const stream = await renderToReadableStream(
<RindleProvider client={db}>
<App />
</RindleProvider>,
);
await stream.allReady;
const app = await new Response(stream).text();
return new Response(
`<!doctype html>
<div id="root">${app}</div>
<script>${db.dehydrateScript()}</script>
<script type="module" src="/client.js"></script>`,
{
headers: {
"Content-Type": "text/html",
"Cache-Control": "private, no-store",
},
},
);
}Call dehydrateScript() once, after the render is done. On a page with no signed-in user,
user is null: let queryFor take that, and refuse what a visitor may not see.
| Option | |
|---|---|
rindle |
Your @rindle/api client |
queries |
(name, args) => query. Your subscribe route’s mapping, for this request’s user. Throw to refuse, as in the route |
userID |
Optional. The same userID your subscribe route passes to db.subscribeOps |
timeout |
How long a query may take, in ms. Default 2,000 |
The Browser Entry
Create db from the page, then hydrate:
import { createClient, RindleProvider } from "@rindle/react";
import { hydrateRoot } from "react-dom/client";
const db = createClient({
base: "/api/rindle",
stream: "https://rindle.example.com",
hydrate: true,
});
hydrateRoot(
document.getElementById("root")!,
<RindleProvider client={db}>
<App />
</RindleProvider>,
);On a page rendered without SSR, hydrate: true does nothing, so the same entry works everywhere.
Loading and Errors
- Slow queries. A query with no rows by
timeoutrendersstatus: "loading". It stays live, and its rows arrive in the browser. - Refused queries. If
queryForrefuses a query, or Rindle can’t keep it live, the hook renderserroron the server, and the browser renders the same error. renderToStringdoesn’t wait for queries. Components render their<Suspense>fallback, and the browser fills them in. Use a streaming renderer that waits, likerenderToReadableStreamwithallReady.
SSR needs React 19. Browser-only rendering works on React 18.
Frameworks
- Hono, Cloudflare Workers, Express, or your own server: as above.
- React Router 7, Remix, TanStack Start: create the SSR client and wrap the app in
RindleProviderin the server entry (entry.server.tsx), which receives the request. - Next.js (App Router): see below.
Next.js
Next.js renders client components on the server without the request, and a server component
can’t hand a client to them as a prop. So the root layout, which has the request, creates the SSR
client and parks it under an id; a client component picks it up by that id during the server
render, and writes the page’s script with useServerInsertedHTML.
// lib/render.ts — server only
import { after, connection } from "next/server";
import {
createSSRClient, type SSRClient,
} from "@rindle/react/server";
import { db as rindle } from "./rindle"; // your @rindle/api client
import { queryFor } from "./queries";
const g = globalThis as { __rindleRenders?: Map<string, SSRClient> };
const renders = (g.__rindleRenders ??= new Map());
// `user` is whoever your routes see as signed in (null for a public
// page).
export async function beginRender(
user: { id: string } | null,
): Promise<string> {
await connection(); // render per request, never at build time
const db = createSSRClient({
rindle,
queries: (name, args) => queryFor(user, name, args),
userID: user?.id,
});
const id = crypto.randomUUID();
renders.set(id, db);
// Once the response is sent, wait for the browser to take the queries
// over, then forget them.
after(async () => {
db.dehydrateScript();
await Promise.race([
db.handedOff,
new Promise((r) => setTimeout(r, 10_000)),
]);
renders.delete(id);
});
return id;
}// app/layout.tsx
import { beginRender } from "@/lib/render";
// However your routes read the signed-in user
import { currentUser } from "@/lib/auth";
import { RindleRoot } from "./RindleRoot";
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const ssrID = await beginRender(await currentUser());
return (
<html lang="en">
<body>
<RindleRoot ssrID={ssrID}>{children}</RindleRoot>
</body>
</html>
);
}// app/RindleRoot.tsx
"use client";
import { useRef, useState, type ReactNode } from "react";
import { useServerInsertedHTML } from "next/navigation";
import {
createClient, RindleProvider, type RindleClient,
} from "@rindle/react";
import type { SSRClient } from "@rindle/react/server";
// One browser client per page load. Kept outside React state, because
// React's development Strict Mode runs state initializers twice, and a
// second hydrating client would take over the queries.
let browserClient: RindleClient | undefined;
export function RindleRoot({
ssrID,
children,
}: {
ssrID: string;
children: ReactNode;
}) {
const [state] = useState(() => {
if (typeof window !== "undefined") {
browserClient ??= createClient({
base: "/api/rindle",
stream: "https://rindle.example.com",
hydrate: true,
});
return { browser: browserClient };
}
const g = globalThis as { __rindleRenders?: Map<string, SSRClient> };
const db = g.__rindleRenders!.get(ssrID)!;
// Count queries still loading, so the script is written once they
// have all arrived.
const loads = new Map<string, Promise<void>>();
let pending = 0;
const client = {
peek: db.peek,
load(name: string, args?: unknown) {
const key = JSON.stringify([name, args ?? null]);
let p = loads.get(key);
if (!p) {
pending++;
p = db.load(name, args).finally(() => pending--);
loads.set(key, p);
}
return p;
},
};
return { server: { db, client, pending: () => pending } };
});
const written = useRef(false);
useServerInsertedHTML(() => {
const server = state.server;
if (!server || written.current || server.pending() > 0) return null;
written.current = true;
const __html = server.db.dehydrateScript();
return <script dangerouslySetInnerHTML={{ __html }} />;
});
const client = state.browser ?? state.server!.client;
return <RindleProvider client={client}>{children}</RindleProvider>;
}Pages then call useQuery("notes") in client components, with no <Suspense> around
the live queries. A complete example, with a Playwright test, is
apps/ssr.
Costs
- Each server-rendered page view holds its queries briefly, until the browser takes over. That includes crawlers and link previews. Skip the provider for known bots if that matters.
- The page grows by the data it shows. About the size of the rows themselves.