Server Rendering with Next.js
Teamboard's team page should arrive with its posts already in the HTML: better for search engines, better on slow
phones, and no spinner before the first paint. The db runs on the server too. Each request gets its own db, the page
loads its queries before rendering, and db.dehydrate() captures the rows. The browser's db starts from them, so its
first render matches the server's, and then it carries on live: refetching stale rows, opening syncs and taking writes.
- Why a module-level db is a data leak on the server, and how to create one per request.
- How to load and dehydrate queries in a Next.js App Router Server Component.
- How to hydrate the client db and read it with
DbProvideranduseDb. - What a hydrated query shows, and what is never dehydrated.
- How the same pattern works with the Pages Router and plain
renderToString.
One db per request
Most DB guides use a module-level db:
export const db = createDb({ post: Post, postSummary: PostSummary });
// On a server, every request shares this one db
That is fine in the browser, where one module serves one user. On a server, one module serves every request. A module-level db would keep Alice's private drafts in memory and show them in Bob's render. Collections, on the other hand, are plain definitions that hold no data, so they can be shared. Export a factory instead:
import { createDb } from "@hyper-fetch/db";
import type { DbOptions } from "@hyper-fetch/db";
const collections = { post: Post, postSummary: PostSummary };
export const createAppDb = (options?: DbOptions) => createDb(collections, options);
export type AppDb = ReturnType<typeof createAppDb>;
Components stop importing db and read it from the nearest DbProvider with
useDb<AppDb>(). The type argument gives back the typed collections.
App Router
The Server Component creates a db, loads what the page shows, and passes the dehydrated state to a Client Component:
import { eq } from "@hyper-fetch/db";
import { createAppDb } from "@/db";
import { TeamFeedRoot } from "./team-feed";
export default async function TeamPage({ params }: { params: Promise<{ teamId: string }> }) {
const { teamId } = await params;
const db = createAppDb();
await db.postSummary.where((post) => eq(post.teamId, teamId)).get();
const state = db.dehydrate();
db.destroy();
return <TeamFeedRoot state={state} teamId={teamId} />;
}
query.get()loads the query and resolves with its first state that is notloading. Like every read, it never throws: a failed load resolves withstatus: "error", and the client loads again on its own.db.dehydrate()returns plain, JSON-safe data, so it crosses the Server/Client boundary as a prop.db.destroy()stops the db's timers once it has served its purpose, so finished requests do not keep it in memory.
The Client Component creates the browser's db once, from that state:
"use client";
import { useState } from "react";
import { eq } from "@hyper-fetch/db";
import type { DehydratedDb } from "@hyper-fetch/db";
import { DbProvider, useDb, useLiveQuery } from "@hyper-fetch/react";
import { createAppDb, type AppDb } from "@/db";
export function TeamFeedRoot({ state, teamId }: { state: DehydratedDb; teamId: string }) {
const [db] = useState(() => createAppDb({ state }));
return (
<DbProvider db={db}>
<TeamFeed teamId={teamId} />
</DbProvider>
);
}
function TeamFeed({ teamId }: { teamId: string }) {
const db = useDb<AppDb>();
const { data, isFetching } = useLiveQuery(
db.postSummary.where((post) => eq(post.teamId, teamId)).orderBy((post) => post.createdAt, "desc"),
);
return (
<ul>
{isFetching && <li className="text-sm text-gray-500">Refreshing...</li>}
{data?.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
useState with an initializer creates the db on the first render and keeps it across re-renders. Creating it in the
component body would start a new db, and drop every loaded row, on every render.
What the first render shows
A hydrated query does not wait for anything:
- On the first render, it is
readywith the server's rows, so the HTML React hydrates matches the server's. - It is also
stale: the rows are as old as the server's response. - When the component subscribes, the query refetches and opens its syncs. Rows the server no longer returns leave, and new ones join.
A query the server did not load starts as loading in the browser, as it would without server rendering. You do not
have to dehydrate every query, only the ones the first paint needs.
isFetching is true during that background refetch, which makes a quiet "Refreshing..." hint possible without hiding
the rows.
What crosses the wire
db.dehydrate() holds the server rows and the loaded subsets of every collection that holds any, with their load times,
as type-tagged JSON. Some things never leave the server:
- Pending writes and optimistic layers. A write still in flight on the server is not shown in the browser.
- The outbox and syncs. Live updates start in the browser, from the browser's own socket.
- Empty collections. They are left out to keep the payload small.
Type-tagged JSON keeps Date, bigint, Map and Set values intact through JSON.stringify. A value of your own
class needs a codec, and the codec has to be passed on both sides:
export const createAppDb = (options?: DbOptions) => createDb(collections, { codecs: [money], ...options });
Putting codecs in the factory is the simplest way to never forget one side. State for a collection the client db does not have is ignored.
Loaders run your requests on the server, with your client's authentication, such as onAuth from the
authentication guide. On the server it has to find the current request's
credentials, not a token kept in a module. When that is not possible, load only public data on the server and let the
browser load the rest: a failed server load only means the browser loads it itself.
Pages Router and other frameworks
The pattern does not depend on the App Router. With the Pages Router, dehydrate in getServerSideProps and hydrate in
the page:
export const getServerSideProps = async ({ params }: { params: { teamId: string } }) => {
const db = createAppDb();
await db.postSummary.where((post) => eq(post.teamId, params.teamId)).get();
const state = db.dehydrate();
db.destroy();
return { props: { state, teamId: params.teamId } };
};
export default function TeamPage({ state, teamId }: { state: DehydratedDb; teamId: string }) {
return <TeamFeedRoot state={state} teamId={teamId} />;
}
With any other server, render inside the request's db and send the state with the HTML:
const db = createAppDb();
await db.postSummary.where((post) => eq(post.teamId, teamId)).get();
const html = renderToString(
<DbProvider db={db}>
<TeamFeed teamId={teamId} />
</DbProvider>,
);
const state = db.dehydrate(); // embed as JSON next to the HTML
db.destroy();
On the client, hydrateRoot the same tree with createAppDb({ state }) in the provider.
Before and after
| Client-only app | SSR-friendly app |
|---|---|
export const db = createDb(collections) | export const createAppDb = (options) => createDb(collections, options) |
Components import db | Components call useDb<AppDb>() under a DbProvider |
| Queries load in the browser | The server awaits query.get() for what the first paint shows |
| Nothing is sent with the page | db.dehydrate() is sent with the page |
createDb(collections) in the browser | createAppDb({ state }) in a useState initializer |
| Codecs on the client | Codecs in the factory, on both sides |
- The page is public and has to be indexed: a blog, a docs page, a profile.
- The first paint matters on slow devices: a feed, a landing page.
- Skip it for screens behind a login that users open once loaded, such as a settings panel. Client rendering with a module-level db is simpler there.
Teamboard's team page arrives with its posts.
- You can create a db per request with a factory, and read it with
DbProvideranduseDb<AppDb>(). - You can load queries with
query.get()and senddb.dehydrate()with the page. - You can hydrate the client with
createAppDb({ state }), ready on the first render and refreshed after. - You know what is never dehydrated, and that codecs belong on both sides.
- You can use the same pattern with the Pages Router or plain
renderToString.