Skip to content

Reading content from a website ​

Websites query their project D1 database directly. Normal reads do not use a CMS gateway or generated HTTP API — the deployed site keeps working even if the control plane is unavailable. Opt-in preview requests use online CMS authorization and an isolated replica.

The default path is Drizzle over the project schema: a Cloudflare D1 binding plus drizzle-orm/d1 gives you fully typed reads end to end. The optional raw-SQL reader and the Kysely dialect below are alternatives for projects that need them, not extra steps every site must take.

Bind the database ​

Add the registered project database as a D1 binding in the site's wrangler.jsonc. Use the same database_id that is registered in Narew for the environment (wrangler d1 list shows it). The ID in this example is a placeholder. MEDIA_BASE_URL mirrors the public base URL configured on the registered media bucket — leave it empty if the example should not construct public asset URLs. This setting does not make the bucket or its objects private. The example also declares the optional preview Durable Object and its SQLite migration; see Preview your website before using them.

json
{
	"name": "narew-blog-site",
	"main": "src/worker.ts",
	"compatibility_date": "2026-10-13",
	"compatibility_flags": ["nodejs_compat"],
	// The D1 database registered in Narew for this environment.
	"d1_databases": [
		{
			"binding": "DB",
			"database_name": "narew-blog",
			"database_id": "00000000-0000-0000-0000-000000000000",
			// Wrangler applies the reviewed Drizzle history from this directory.
			"migrations_dir": "drizzle",
		},
	],
	"durable_objects": {
		"bindings": [{ "name": "NAREW_SESSIONS", "class_name": "ContentSession" }],
	},
	"migrations": [
		{ "tag": "preview-v1", "new_sqlite_classes": ["PreviewReplica"] },
		{
			"tag": "content-session-v1",
			"renamed_classes": [{ "from": "PreviewReplica", "to": "ContentSession" }],
		},
	],
	"vars": {
		// Public base URL configured on the registered media bucket
		// (Dashboard → Media → Storage). Empty only disables URL construction;
		// bucket access is configured separately.
		"MEDIA_BASE_URL": "https://pub-00000000000000000000000000000000.r2.dev",
		// Set once for this environment. NAREW_SESSION_PUBLIC_JWK is a public verification key.
		"NAREW_CMS_ORIGIN": "",
		"NAREW_SESSION_PUBLIC_JWK": "",
	},
}

wrangler types can generate the Env interface from this file automatically.

Typed client ​

Create the client per request and reuse the project schema — the dashboard and the website then share one source of truth, and every column reference is type-checked. __narew_* tables stay out of the application schema; media assets are the only metadata table a site joins, and only through parameterized SQL. For an authorized preview request, the Worker passes the replica binding instead of public D1.

ts
import { drizzle } from "drizzle-orm/d1";
import * as schema from "./schema.ts";
import type { ContentSessionEnv, ContentSelection } from "@narew/content";

/** Worker bindings plus deployment vars for the public site. */
export interface SiteEnv extends ContentSessionEnv {
	DB: D1Database;
	MEDIA_BASE_URL: string;
	CONTENT_CACHE?: KVNamespace;
}

export type Selection = ContentSelection;

/** One D1 binding plus the project schema gives typed queries end to end. */
export function createContentDatabase(env: SiteEnv) {
	return drizzle(env.DB, { schema });
}

export type Post = typeof schema.posts.$inferSelect;
export type Author = typeof schema.authors.$inferSelect;

Queries ​

Publication and moderation on the website are schema conventions — the CMS does not intercept reads, so filter status, published_at, or approval flags on every public query. Do not skip these filters on a publicly reachable site: that would expose drafts without authorization. The example additionally allows the selected post in an authorized preview; unrelated drafts remain filtered. The selected key is supplied by the preview runtime, not by a URL or an untrusted client parameter. An update-mode session always carries the selected record's key; a create-mode session reports null until the first valid draft row exists, then it carries the new row's key.

If your schema supports scheduled publication with published_at, require that date to be non-null and no later than the current time as well as checking the status. For a Drizzle timestamp column stored in seconds, for example:

ts
const published = and(
	eq(posts.status, "published"),
	isNotNull(posts.publishedAt),
	lte(posts.publishedAt, sql`(unixepoch())`),
);

The documentation's blog schema has no published_at; its published status alone does not provide scheduled publication.

richText fields store Tiptap JSON; render them with renderProseHtml from @narew/core/prose rather than trusting raw HTML.

Localized fields ​

Localized fields (localized.text(), localized.richText()) store language-keyed JSON objects ({ [locale: string]: value }). Websites read these columns directly from D1 (or from the session replica during preview) using the lightweight @narew/core/localized-read module:

ts
import { canonicalizeLocale, resolveLocalized } from "@narew/core/localized-read";
import { renderProseHtml } from "@narew/core/prose";

const localization = {
	locales: ["en", "pl", "es"],
	defaultLocale: "en",
	fallback: true,
};

const resolvedTitle = resolveLocalized(post.title, currentLocale, localization);
const titleText = resolvedTitle.value ?? "Untitled";

const resolvedContent = resolveLocalized(post.content, currentLocale, localization);
const contentHtml = resolvedContent.value ? renderProseHtml(resolvedContent.value) : "";
  • Zero-runtime overhead: @narew/core/localized-read is a minimal module containing only locale canonicalization and fallback resolution. It never pulls in Valibot schemas, CMS validators, or dictionary parsers into the website bundle.
  • Empty string vs missing: An explicit empty string ("") is treated as a valid value and does not trigger a fallback. Missing locale keys or explicit null values fall back to defaultLocale when fallback: true.
  • Preview preservation: During live preview, unsaved edits to the active locale are merged in memory on the replica without modifying other locales and without writing to the source D1 database.

Image and gallery fields store asset IDs. Resolve the object_key from __narew_media_assets and prepend the bucket's public base URL. Keys are content-addressed (assets/…/{id}/{sha256}), so URLs are stable and immutable-cacheable; assets without a public base URL return null and the site should fall back instead of proxying objects.

Narew does not configure or verify a bucket's public-access settings. A file can be public even when no public base URL is configured in Narew, including a file used only in a draft. The authenticated Narew file endpoint checks current media permissions, but this does not restrict other bucket URLs. Moving an asset to trash hides it in Narew but does not delete its R2 object; an existing public URL may still work. Even after an object is deleted outside Narew, cached copies may remain available. Do not treat draft status or trash as a privacy control.

ts
import { renderProseHtml } from "@narew/core/prose";
import { and, desc, eq, or, sql } from "drizzle-orm";
import { createContentDatabase } from "./db/client.ts";
import { authors, posts } from "./db/schema.ts";
import type { Post, Selection, SiteEnv } from "./db/client.ts";

function visiblePosts(selection: Selection) {
	const id =
		selection?.collectionId === "posts"
			? selection.key.find((item) => item.field === "id")?.value
			: null;
	return typeof id === "number" && Number.isSafeInteger(id)
		? or(eq(posts.status, "published"), eq(posts.id, id))
		: eq(posts.status, "published");
}

/** Public requests see published posts; preview may also see the selected post. */
export async function listVisiblePosts(env: SiteEnv, selection: Selection, limit = 20) {
	return await createContentDatabase(env)
		.select()
		.from(posts)
		.where(visiblePosts(selection))
		.orderBy(desc(posts.createdAt))
		.limit(limit);
}

/** One visible post with its author resolved through a typed join. */
export async function getVisiblePost(env: SiteEnv, selection: Selection, slug: string) {
	const [row] = await createContentDatabase(env)
		.select({ post: posts, author: authors })
		.from(posts)
		.innerJoin(authors, eq(posts.authorId, authors.id))
		.where(and(eq(posts.slug, slug), visiblePosts(selection)))
		.limit(1);
	return row;
}

/** richText fields hold Tiptap JSON; render through the shared safe renderer. */
export function renderPostContent(post: Pick<Post, "content">) {
	return post.content === null ? "" : renderProseHtml(post.content);
}

/** Media fields store asset IDs; public URLs combine object_key with the base. */
export async function mediaUrl(env: SiteEnv, assetId: string) {
	const [asset] = await createContentDatabase(env).all<{ objectKey: string }>(
		sql`select object_key as objectKey from "__narew_media_assets"
			where id = ${assetId} and status = 'ready' and deleted_at is null limit 1`,
	);
	if (!asset || !env.MEDIA_BASE_URL) {
		return null;
	}
	return `${env.MEDIA_BASE_URL}/${asset.objectKey}`;
}

Collections configured with orderField sort ascending with NULLs last, matching the dashboard ordering:

ts
const ordered = await db
	.select()
	.from(categories)
	.orderBy(sql`${categories.position} nulls last`, asc(categories.id));

Singletons are ordinary tables that hold at most one row — select with .limit(1) and handle the missing row.

Worker entrypoint ​

resolveContentEnv runs before any content query. It returns either a response to send unchanged (preview protocol requests and preview failures) or a ready result whose env already holds the right database: public D1 normally, or the session's isolated replica during an authorized preview. Pass the result's finish the final response, and its fail any error. Public responses and errors pass through unchanged; preview responses get private no-store and frame headers plus the iframe client, and preview errors become a safe error page (documents) or { "error": code } JSON.

ts
import { withSharedContentCache } from "@narew/content";
import { getVisiblePost, listVisiblePosts, renderPostContent } from "./content.ts";
// Generated by `narew-cms content env`; regenerating refreshes the D1 bindings.
import { resolveContentEnv } from "./narew-content.ts";
import type { Selection, SiteEnv } from "./db/client.ts";

export { ContentSession } from "@narew/content";

function escapeHtml(value: string): string {
	return value
		.replaceAll("&", "&amp;")
		.replaceAll("<", "&lt;")
		.replaceAll(">", "&gt;")
		.replaceAll('"', "&quot;");
}

function html(body: string, status = 200): Response {
	return new Response(
		`<!doctype html><html><head><title>Narew Blog</title></head><body>${body}</body></html>`,
		{
			status,
			headers: { "Content-Type": "text/html; charset=utf-8" },
		},
	);
}

export default {
	async fetch(request: Request, env: SiteEnv): Promise<Response> {
		const site = await resolveContentEnv(request, env);
		if (site.kind === "response") {
			return site.response;
		}
		try {
			const url = new URL(request.url);
			url.searchParams.delete("__narew_session");
			const cache = env.CONTENT_CACHE;
			if (!cache || request.method !== "GET" || url.search || url.pathname.length > 480) {
				return site.finish(await handle(request, site.env, site.selection));
			}
			const key = `blog:${url.pathname}`;
			const response = await withSharedContentCache(site, {
				read: async () => {
					const value = await cache.get(key);
					return value === null
						? null
						: new Response(value, {
								headers: { "Content-Type": "text/html; charset=utf-8" },
							});
				},
				load: () => handle(request, site.env, site.selection),
				write: async (value) => {
					if (value.status === 200) {
						await cache.put(key, await value.clone().text(), { expirationTtl: 60 });
					}
				},
			});
			return site.finish(response);
		} catch (error) {
			return site.fail(error);
		}
	},
};

async function handle(request: Request, env: SiteEnv, selection: Selection): Promise<Response> {
	if (request.method !== "GET") {
		return new Response("Method not allowed", { status: 405 });
	}
	const path = new URL(request.url).pathname;
	if (path === "/") {
		const posts = await listVisiblePosts(env, selection);
		const links = posts.map(
			(post) =>
				`<li><a href="/${encodeURIComponent(post.slug)}">${escapeHtml(post.title)}</a></li>`,
		);
		return html(`<h1>Posts</h1><ul>${links.join("")}</ul>`);
	}
	const slug = decodeURIComponent(path.slice(1));
	const row = await getVisiblePost(env, selection, slug);
	return row
		? html(
				`<a href="/">Posts</a><h1>${escapeHtml(row.post.title)}</h1>` +
					`<p>${escapeHtml(row.author.name)}</p>${renderPostContent(row.post)}`,
			)
		: html('<a href="/">Posts</a><p>Not found</p>', 404);
}

The example's root path lists visible posts, and /<slug> shows a post. A new record appears in the list once its required fields are valid. Websites with different routing should link to their own previewable pages; the CMS cannot infer every site's URL structure.

Optional raw-SQL reader ​

createContentReader is for parameterized SQL when you do not want a query builder. Drizzle remains the default. Pass the request site; the reader uses site.env.DB, so preview automatically reads the replica instead of public D1. Pass the site's KV namespace to cache public results as a JSON array. A content session never reads or writes that namespace, including when a public entry already exists.

cacheKey is a prefix, not the whole entry name. The final KV key hashes the binding, version, SQL and parameters, so two queries cannot share an entry by accident. Omit cache, or a query's cacheKey, to always read D1. ttl is 60 through 31,536,000 seconds and defaults to 60. rows() returns the list. first() returns the first row of that same cached list, so add LIMIT 1 when one record is enough. The helper rejects writes and does not add publication filters: keep those in your SQL.

To automate cache invalidation across CMS edits, pass databaseId (or an explicit versionKey override):

  • Automatic CMS invalidation: Every successful record mutation (create, update, publish, delete) in a CMS environment with registered KV cache increments a shared version key in KV (narew:v:<databaseId>).
  • Single version read: createContentReader fetches this version key once per reader instance and includes it in the query cache key (narew:q:<v>:<hash>). When content changes in the CMS, subsequent queries automatically read from the new version key without requiring manual cache purges, even with a long ttl. If no databaseId or versionKey is provided, version defaults to "0".
  • Zero-touch preview: In preview sessions (site.isSession === true), the reader bypasses KV entirely, never fetching the version key and never reading or writing cached data.

The cache is best effort. A failed KV read counts as a miss, and a failed KV write never fails the D1 response — important because KV rate-limits writes to one per key per second. Callers that need strict cache semantics should use withSharedContentCache directly.

selectedField(site.selection, collectionId, field) returns one authorized preview key field, or null for a public request, another collection, or a missing field. It is only safe for single-field keys. For compound keys use selectedKey(site.selection, collectionId), which returns every field, and match all of them in the predicate.

ts
import { createContentReader, selectedField } from "@narew/content";

const reader = createContentReader({
	site,
	...(site.env.CONTENT_CACHE ? { cache: site.env.CONTENT_CACHE } : {}),
	databaseId: "db_0123456789abcdef",
	ttl: 3600,
});
const posts = await reader.rows<{ id: number; title: string }>({
	sql: `SELECT id, title FROM posts
		WHERE status = 'published' OR id = ? ORDER BY id`,
	params: [selectedField(site.selection, "posts", "id")],
	cacheKey: "site:/posts",
});

@narew/content/read exports the same functions. The Hono example uses this reader; the blog example keeps Drizzle.

Kysely ​

For Kysely, @narew/content/kysely provides a read-only D1 dialect. Pass it the same request-selected database; DB is your site's own Kysely schema type:

ts
import { createD1ReadDialect } from "@narew/content/kysely";
import { Kysely } from "kysely";

const db = new Kysely<DB>({ dialect: createD1ReadDialect(site.env.DB) });

Only execute this after handling site.kind === "response". Apply the same publication/selected-record filtering. The dialect rejects writes and transactions for both public D1 and preview; it is not a full D1 write adapter. It is an advanced alternative, not a requirement.

Preview database compatibility ​

The replica implements the D1 read subset that Drizzle and Kysely use: prepare, bind, all, first, raw, run (reads only) and read-only batch. The optional reader uses prepare, bind, and all from that subset. A batch runs on one consistent snapshot, accepts at most 64 statements, and rejects entirely if any statement writes. exec, dump, bookmarks, writes, transactions and savepoints are rejected and never reach the source D1. Results, including BLOB values and duplicate column names, match native D1 in the local parity tests. Other D1 query builders work only within this subset; verify them with your own fixture before relying on them.

Preview errors ​

Errors from the replica, such as SOURCE_CHANGED after content is saved elsewhere, surface in your handler like any query error. Route them through site.fail(error). To customize the page, pass onSessionError in the options argument of resolveContentEnv; it receives a sanitized { code, status, message } and renders only document navigations. The status and protective headers are always enforced. A thrown Response keeps its own status. Use contentSessionError(error) in framework error boundaries to read the same sanitized value; application errors, including forged messages, become UNAVAILABLE. Errors after a streamed response has started cannot replace bytes already sent.

Request scope, caches and background work ​

Query only through site.env (or values derived from it in the request). Reading a binding captured at module scope, import { env } from "cloudflare:workers", or a client created outside the request bypasses the replica and shows saved content in the iframe; Narew cannot detect this.

Skip application caches during preview: do not read or write Cache API, KV or in-memory render caches when site.isSession is true. The withSharedContentCache(site, { read, load, write }) helper calls only load in a session; for a public request it returns a non-null cache hit, otherwise loads and writes the result. It is the strict building block: the caller owns cache keys, serialization, TTL, invalidation and failure policy. createContentReader wraps it, hashes query keys and treats cache failures as best effort. Do not use a shared cache for user-specific data or bypass the helper elsewhere in the request.

The blog and Hono examples show optional CONTENT_CACHE KV integration. Without that binding their public behavior remains uncached; adding a real KV namespace and its invalidation policy is a separate deployment decision. No namespace is copied or replaced for sessions. Response headers alone do not stop application code from caching a draft. Work in ctx.waitUntil() may keep using site.env while the session is valid; it fails closed when it expires.

Hono ​

@narew/content/hono installs the request scope once. The adapter resolves site, shares it through the context, protects session responses and routes errors through finish/fail:

ts
import { createContentEnvHono } from "@narew/content/hono";

const contentEnv = createContentEnvHono<Env, "DB">(resolveContentEnv);
app.use(contentEnv.middleware);
app.onError(contentEnv.onError);

onError rethrows session failures so the middleware renders them once; other errors stay a plain 500. The example below is the complete Worker:

ts
import { createContentReader, selectedField } from "@narew/content";
import { createContentEnvHono } from "@narew/content/hono";
import { Hono } from "hono";
// Generated by `narew-cms content env`; regenerating refreshes the D1 bindings.
import { resolveContentEnv } from "./narew-content.ts";
import type { ContentEnvResult, ContentSessionEnv } from "@narew/content";

export { ContentSession } from "@narew/content";

interface Env extends ContentSessionEnv {
	DB: D1Database;
	CONTENT_CACHE?: KVNamespace;
}
type Site = Extract<ContentEnvResult<Env, "DB">, { kind: "ready" }>;

const contentEnv = createContentEnvHono<Env, "DB">(resolveContentEnv);
const app = new Hono<{ Bindings: Env; Variables: { site: Site } }>();

app.use(contentEnv.middleware);
app.onError(contentEnv.onError);

app.get("/posts", async (c) => {
	const site = c.var.site;
	const { env } = site;
	const url = new URL(c.req.url);
	url.searchParams.delete("__narew_session");
	const reader = createContentReader({
		site,
		...(env.CONTENT_CACHE ? { cache: env.CONTENT_CACHE } : {}),
	});
	const rows = await reader.rows<{ id: number; title: string }>({
		sql: "SELECT id, title FROM posts WHERE status = 'published' OR id = ? ORDER BY id",
		params: [selectedField(site.selection, "posts", "id")],
		...(url.search ? {} : { cacheKey: "hono:/posts" }),
	});
	c.header("Cache-Control", "public, max-age=300");
	c.header("Content-Type", "application/json; charset=utf-8");
	return c.body(JSON.stringify(rows));
});

export default app;

Beyond Workers ​

The supported website integration uses a direct D1 Worker binding. Narew's Cloudflare REST adapters belong to the CMS API and are not copied into websites. Keep Cloudflare account credentials out of website configuration.

Conventions ​

  • Read only. Websites never write — direct SQL writes bypass receipts, permissions, and schema checks.
  • Filter publication state and moderation flags on every public query.
  • Treat __narew_* tables as read-only metadata; __narew_media_assets is the documented read surface.
  • Copy the packages under packages/ beside core — content and cli join when adding live preview; they do not need the CMS API, dashboard, or a link back to this repo.

See also Preview your website for installation, local testing and limitations, and Package portability for copying these packages outside the monorepo.