Server rendering with Kovlet (Next.js, Nuxt, SvelteKit)
Show live Kovlet data in client components, and render real data on the server with a key that never leaves it. This guide covers both, for Next.js, Nuxt and SvelteKit.
On this page
At a glance
- Create the Kovlet client and use its hooks in client components only. Render them with
ssr: false,<ClientOnly>orssr = false. - On the server, read data with
createServerReaderfrom@kovlet/client/server. - The server authenticates with a Machine Auth Key, kept in a server-only environment variable.
- Never give the key a public prefix (
NEXT_PUBLIC_,VITE_,PUBLIC_). Browser bundles of@kovlet/client/serverthrow instead of shipping it.
Prerequisites
- A Next.js (App Router), Nuxt or SvelteKit app with
@kovlet/clientinstalled, and@kovlet/reactfor React. The web quickstart sets them up. - A Data Space with a table to render, such as
expenses. - For server-rendered data: an owner or admin who can create a Machine Auth Key in the console.
Two kinds of data, two places
Kovlet apps keep a copy of the data in the browser and sync it live. That's why live data belongs to client components. The server can still render real data: it reads over REST with a Machine Auth KeyA key (kvm_…) created in the console for an unattended server, exchanged for a session token. that never leaves the server.
| What | Where it runs | How it authenticates |
|---|---|---|
Live, per-user data: useTable, useFiles, useSyncStatus, offline writes | The browser (client components) | The user signs in through Kovlet's consent page. No key in the app. |
| A first paint, public pages, feeds, sitemaps, emails | The server (Server Components, route handlers, load, server routes) | A Machine Auth Key, read from a server-only environment variable. |
Keep them apart. A browser client never gets the machine key. The server never pretends to be a signed-in user.
Step 1: Live data: create the client in the browser only
createKovletClient belongs to the browser. On the server it has no user to sign in. In Node, its default sign-in is the /activate device flow, which is wrong inside a web request.
Follow two rules:
- Create the client with
autoConnect: falsein a module that only client components import. - Render the components that use Kovlet hooks on the client only.
Why the second rule? The local copy of the data (the replica) lives in IndexedDB, so the server can't render the same rows. A server-rendered empty list would not match the browser's first render. That's a hydration mismatch.
Next.js (App Router)
// app/expenses/kovlet.ts
"use client";
import { createKovletClient, t } from "@kovlet/client";
export const kovlet = createKovletClient({
appName: "Receipt Scanner",
autoConnect: false, // connect from a click so the consent popup isn't blocked
spaces: {
finance: { role: "editor", tables: { expenses: { vendor: t.string(), amount: t.number() } } },
},
});
// A stored session resumes on later loads without a popup.
void kovlet.ready.then(() => kovlet.session && kovlet.connect().catch(() => {}));// app/expenses/LiveExpenses.tsx
"use client";
import { KovletProvider, useSpace, useSyncStatus, useTable } from "@kovlet/react";
import { kovlet } from "./kovlet";
function Expenses() {
const status = useSyncStatus();
const finance = useSpace<typeof kovlet>("finance");
const rows = useTable(finance.table("expenses"), { orderBy: "vendor" });
if (status.state === "signed-out") return <button onClick={() => kovlet.connect()}>Connect to Kovlet</button>;
return <ul>{rows.map((r) => <li key={r.id}>{r.vendor}: {r.amount}</li>)}</ul>;
}
export default function LiveExpenses() {
return (
<KovletProvider client={kovlet}>
<Expenses />
</KovletProvider>
);
}Load the live component from a page with ssr: false:
// app/expenses/page.tsx (a Server Component)
import dynamic from "next/dynamic";
const LiveExpenses = dynamic(() => import("./LiveExpenses"), { ssr: false, loading: () => <p>Loading…</p> });
export default function Page() {
return <LiveExpenses />;
}ssr: false keeps the module, and so createKovletClient, off the server.
Note Some Next.js versions require dynamic(..., { ssr: false }) to be called from a client component. There, wrap it in a small "use client" file.
Nuxt
Create the client in a client-only plugin (plugins/kovlet.client.ts). The plugin runs app.use(createKovlet(kovlet)) from @kovlet/vue. Wrap Kovlet-driven components in <ClientOnly>.
SvelteKit
Do one of these:
- Create the client in a module imported only from the browser (
if (browser)from$app/environment). - Turn off server rendering for the routes that use it (
export const ssr = falsein+page.ts).
Then call setKovlet(kovlet) from @kovlet/svelte in the layout.
React Native and Expo
Nothing to do. There is no server render. Use @kovlet/react-native.
Step 2: Server-rendered data: a Machine Auth Key, server-only
For data the server renders itself, the server needs its own key:
- Create a Machine Auth Key in the console (Access → Machines → Add server).
- Grant it a role on the Data Space for your app.
- Put it in a server-only environment variable, for example in
.env.local.
Caution Never give the variable a NEXT_PUBLIC_, VITE_ or PUBLIC_ prefix.
KOVLET_MACHINE_KEY=kvm_...
KOVLET_CLIENT_ID=<your app's id from the console>
KOVLET_SPACE_ID=<the Data Space's id>Reading over REST needs a token exchange, a token cache, pagination and turning stored records into rows. @kovlet/client/server does exactly that and nothing else.
// lib/kovlet-server.ts
import "server-only"; // Next.js: a build error if a client component imports this file
import { createServerReader } from "@kovlet/client/server";
export const kovletServer = createServerReader({
machineKey: process.env.KOVLET_MACHINE_KEY!,
clientId: process.env.KOVLET_CLIENT_ID!,
// url: "https://api.kovlet.com" (default)
});// app/reports/page.tsx (a Server Component)
import { kovletServer } from "@/lib/kovlet-server";
export const dynamic = "force-dynamic"; // or `export const revalidate = 60`
export default async function Report() {
const expenses = await kovletServer.rows<{ vendor: string; amount: number }>(process.env.KOVLET_SPACE_ID!, "expenses");
const total = expenses.reduce((sum, e) => sum + e.amount, 0);
return <p>{expenses.length} expenses, {total.toFixed(2)} in total</p>;
}createServerReader({ machineKey, clientId, url?, fetch? }) | |
|---|---|
rows<T>(spaceId, table, { trashed? }) | Every live row of a table as { id, ...fields }, all pages. trashed: "include" | "only" for the Trash. |
files(spaceId, { prefix? }) | File metadata (id, path, mime_type, size_bytes, sha256, version, …). |
fileUrl(spaceId, fileId) | A short-lived presigned download URL, e.g. for an <img> the server renders. |
transact(spaceId, writes, { batchId? }) | Writes several rows, across tables, all or nothing (POST /v1/spaces/{space}/transact). Each write is { op: "insert" | "update" | "delete" | "restore", table, id?, fields? }. A rejected batch throws TransactionRejectedError with the failing write's index and code, and applies nothing. Pass the same batchId to retry safely. |
request<T>(method, path, body?) | Any other REST route as the machine, e.g. GET /v1/spaces/{space}/activity. |
You should see
- The totals in the page's HTML source, for example
<p>3 expenses, 42.50 in total</p>. The server rendered them. - No key or token in the browser.
The reader caches its token in memory until shortly before it expires. It gets a new one when the server answers 401.
For writes from a request handler (a form action, a webhook), use transact. It's one HTTP call, all or nothing, with no socket.
For a server process that keeps a live replica and syncs continuously, run createKovletClient({ auth: { type: "machine-key", machineKey, clientId }, spaces: { finance: { spaceId } } }) instead.
Keep the key out of the client bundle
- Read the key from
process.envin a server-only module. Never give the variable aNEXT_PUBLIC_,VITE_orPUBLIC_prefix. Those are copied into the browser bundle. - Import
server-only(Next.js) or keep the module undersrc/lib/server/(SvelteKit's server-only folder) orserver/(Nuxt). @kovlet/client/serverrefuses to run in a browser. Its package export resolves to a stub that throws under thebrowsercondition. It also throws if it finds awindowand adocument. If a client component imports it by mistake, the page fails loudly instead of shipping a key.- Pass data from the server to client components as props, never the key or a token.
Step 3: Use both on one pageOptional
Render the server snapshot as plain HTML for the first paint. Mount the live list on the client. Once it's live, the client list replaces the snapshot.
// app/expenses/page.tsx
import { kovletServer } from "@/lib/kovlet-server";
import LiveExpensesLoader from "./LiveExpensesLoader"; // "use client" + dynamic(..., { ssr: false })
export default async function Page() {
const initial = await kovletServer.rows<{ vendor: string; amount: number }>(process.env.KOVLET_SPACE_ID!, "expenses");
return <LiveExpensesLoader fallback={<ul>{initial.map((r) => <li key={r.id}>{r.vendor}</li>)}</ul>} />;
}Caution The machine sees what its grant allows. The signed-in user sees what their own role and the app's consent allow. These can differ. So only server-render data that every viewer of the page may see.
Checklist
createKovletClientis only ever evaluated in the browser ("use client"module, loaded withssr: false/<ClientOnly>/ssr = false).- Hooks (
useTable,useFiles, …) live in client components only. KOVLET_MACHINE_KEYhas no public prefix and is only read in server-only modules.- Server pages that read with the machine key render only data every visitor may see.
Next
- Kovlet errors and limits reference: what the REST reads can answer.
- Access model: Users × Machines × Applications: why a machine and a signed-in user can see different rows.
- Kovlet sync protocol reference: the REST routes
@kovlet/client/servercalls.
Ready to try it? Start free. No credit card, no API keys.
For coding agents: this page is also Markdown. Add .md to the URL or send Accept: text/markdown. The full reference is at /llms-full.txt.