Skip to content

Preview your website ​

Copy collections between environments ​

The collection copy dialog estimates the source row count and how many source keys match records in the destination. Matching keys can overwrite destination records. Counts are observations, not a reservation: data can change before the copy, and other database constraints can cause a later batch to fail. Preview requires read permission in both environments and create/update permission in the destination. Copying to production also requires explicit confirmation.

The source must fit in one bounded response: at most 10,100 rows and the API's 8 MiB response limit, including provider and metadata overhead. If it does not fit, copying fails before any destination writes. Source records are read in one query; subsequent changes do not update that already captured copy.

Destination writes run in batches, not one transaction for the whole collection. If the response or a batch is lost, some records may already have changed. The dashboard retains the operation ID in the current browser tab across reloads; check its status and inspect the destination before explicitly clearing the warning or starting another copy. Closing the tab can discard this recovery information. Status checking does not replay writes, and a partially applied copy may remain pending.

Preview opens your actual website in the dashboard iframe. When you select a record, the CMS issues a short-lived session for the signed-in editor, the selected environment, registered D1 and collection. The site takes a bounded snapshot of that D1 into a session-specific Durable Object. Unsaved edits are applied to that isolated copy, and the website reads the copy for preview requests. Other visitors keep reading D1 directly.

When editing localized collections, the dashboard provides an independent content locale switcher, separate from the dashboard UI language. Unsaved edits merge only the active locale's values, preserving all other languages without data loss. The editor includes a Copy from default action to pull in text from the default locale without silently overwriting saved content. Localized JSON columns are excluded from database-level sorting and filtering. Live preview reflects edits in the chosen locale immediately in the website iframe without touching the source D1.

Save is still a CMS action: it writes to the registered D1. The dashboard then starts a fresh preview from the saved data. A failed save leaves the unsaved edit in the editor. Preview itself never writes the source D1.

The website opts in once, at its Worker entrypoint, with @narew/content. See the complete Worker example. You do not manually call loadContentBinding in ordinary website code.

Prerequisites ​

  • A website using a Cloudflare Worker, a D1 binding and SQLite Durable Objects.
  • A CMS organization, project and environment, with the site's D1 registered and its Narew metadata installed. The editor needs content.read and the relevant content.create or content.update permission.
  • The environment's website URL must have the origin of the site shown in the iframe. Use HTTPS, or loopback HTTP for local development. The CMS and site must have different origins. Members with projects.manage can save that URL for the whole team; the dashboard also accepts a per-browser link scoped to each organization/project/environment whose origin must match the environment's configured URL for live preview.
  • A P-256 signing key configured as PREVIEW_SIGNING_KEY on the CMS API. Keep the private JWK in the CMS secret store. Only the matching public JWK goes to the site, serialized as NAREW_SESSION_PUBLIC_JWK; set NAREW_CMS_ORIGIN to the CMS's canonical public origin. Never put the private key or Cloudflare API credentials in the website.
  • A browser that supports partitioned third-party cookies. The local browser tests use Chromium; other browser policies have not been verified.

NAREW_CMS_ORIGIN, NAREW_SESSION_PUBLIC_JWK and the DO binding can be set per Worker environment; the site does not switch origins in its request-handling code. Ordinary public reads do not need preview configuration or a CMS connection.

Generate the key pair once with Web Crypto — preview-signing-key.jwk.json is the PREVIEW_SIGNING_KEY value, and public-jwk.json is the site's NAREW_SESSION_PUBLIC_JWK plus the content bind --public-key file:

sh
node --input-type=module <<'EOF'
const { writeFile } = await import("node:fs/promises");
const pair = await crypto.subtle.generateKey(
	{ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"],
);
await writeFile("preview-signing-key.jwk.json",
	JSON.stringify(await crypto.subtle.exportKey("jwk", pair.privateKey), null, "\t") + "\n");
await writeFile("public-jwk.json",
	JSON.stringify(await crypto.subtle.exportKey("jwk", pair.publicKey), null, "\t") + "\n");
EOF

Install the signed binding ​

The signed binding is an installation record, not a session credential. It contains the issuer, site audience and organization/project/environment/D1 registration scope. The preview runtime reads and verifies it internally after online session authorization; it is not an authorization grant.

A member holding databases.manage and schema.manage can obtain the binding bundle directly in the dashboard UI under Environment → Preview setup, or through the authenticated endpoint:

text
POST /v1/organizations/:org/projects/:project/environments/:env/databases/:registration/content-binding

The endpoint returns { "binding": "...", "cmsOrigin": "...", "publicJwk": { ... } }, exporting only the public JWK verification parameters (kty, crv, x, y) without exposing private keys. In the dashboard UI, you can download this payload as narew-preview-binding.json and copy the one-line CLI installation command.

Use the exported file to append a custom migration to the existing Drizzle history of the project that owns the database — the content project in a split content/website setup, or the same workspace in a combined one. The metadata history must exist first — run narew-cms generate before binding:

sh
pnpm exec narew-cms content bind --from-file ./narew-preview-binding.json

Alternatively, you can provide the three individual options:

sh
pnpm exec narew-cms content bind \
	--binding artifact.json \
	--public-key public-jwk.json \
	--cms-origin https://cms.example.com

--from-file cannot be combined with --binding, --public-key or --cms-origin.

Review the generated migration before applying it to the registered D1. --check exits 1 with BINDING_DRIFT when a new migration is due; --dry-run reports the change without writing. Neither applies SQL. The command also writes drizzle/narew.content-binding.snapshot.json, recording the installed claims and verification key — commit it together with the migration. Installing a different binding over an existing one stops with REQUIRES_REPLACE unless --replace is passed. The binding table stores one installation; use a separate D1 for a different environment or audience rather than overwriting production's binding.

A signed row can be copied to another database, so the signature alone does not prove the physical identity of D1. The generated environment module below is the additional trusted configuration mapping the authorized D1 ID to the Worker's actual binding.

Generate the content environment module ​

The module must be generated from the same Wrangler configuration, environment and mode used to run or deploy the site, in the website's workspace. It maps binding names and D1 IDs to Worker binding objects. content env writes src/narew-content.ts (--output overrides it):

sh
pnpm exec narew-cms content env --mode deployment
pnpm exec narew-cms content env --mode local
pnpm exec narew-cms content env --mode deployment --check

Choose the mode matching your environment:

  • --mode deployment: Used for deployed production or staging Workers. Always uses database_id.
  • --mode remote-dev: Used for Wrangler remote development against remote Cloudflare databases (remote: true). Prefers preview_database_id over database_id.
  • --mode local: Used for local development with local bindings. Rejects any binding marked remote: true.

For a named Wrangler environment, add --environment staging (or your environment name) and run Wrangler with that same environment. Register that exact database ID in the selected CMS environment. Regenerate and check before each different build or development mode. The generator reads configuration and writes source; it does not change Cloudflare resources or prove that a deployed Worker matches the file.

The example module is generated from the example Wrangler file. Its zero ID is a placeholder: replace it with your registered D1 ID before generating.

ts
// Generated from Wrangler configuration by `narew-cms content env`. Regenerate when
// that configuration changes. A databaseId is deployment configuration, never
// authorization.
import { createContentEnvResolver } from "@narew/content";

export const resolveContentEnv = createContentEnvResolver(
	(env: { DB: D1Database }) =>
		[
			{
				binding: "DB",
				databaseId: "00000000-0000-0000-0000-000000000000",
				database: env.DB,
			},
		] as const,
);

Local development ​

Narew provides a symmetrical, zero-configuration local development workflow where local environments (kind: "local") mirror production semantics without touching Cloudflare accounts or credentials.

1. Initialize and start the CMS ​

Before the first run, initialize local secrets:

sh
pnpm dev:init
pnpm dev
  • pnpm dev:init (scripts/dev-init.ts) generates apps/api/.dev.vars (AUTH_SECRET, CREDENTIAL_KEYS, and a P-256 PREVIEW_SIGNING_KEY) atomically (wx), never overwriting existing secrets. Optional settings are documented in apps/api/.dev.vars.example.
  • pnpm dev (and pnpm dev:local) runs scripts/dev-local.ts:
    1. Applies reviewed D1 control migrations automatically to the local persistence directory (NAREW_LOCAL_STATE, defaulting to apps/api/.wrangler/state).
    2. Launches the dashboard at http://localhost:7700 and the API at http://localhost:7701.

2. Local environments (kind: "local") ​

In local development mode, projects can have one or more environments with kind: "local", indicated with a Local only badge in the dashboard:

  • Isolation: Local environments exist and appear only when running the local CMS. On remote or production deployments, local environments are filtered from lists, cannot be created, and direct access by ID returns NOT_FOUND.
  • Remote project resources: Local environments connect to remote Cloudflare project resources (remote: true for D1, R2, and KV), allowing developers to preview their actual content locally (websiteUrl: http://localhost:7730).

3. Register resources in the dashboard ​

Under the selected environment:

  • D1 Database: Open Bindings → Databases and register your remote Cloudflare D1 database.
  • R2 Storage: Open Bindings → Media buckets and register your remote Cloudflare R2 bucket.
  • KV Cache: Open Bindings → KV cache (/bindings/cache) and register your remote Cloudflare KV cache namespace.

4. Bind preview in your website project ​

  1. In the CMS dashboard, navigate to your environment's Preview setup card.
  2. Download narew-preview-binding.json (or copy the displayed command).
  3. In your website workspace, run:
sh
pnpm exec narew-cms content bind --from-file ./narew-preview-binding.json

This appends the custom migration to your Drizzle history; review and apply it to your database.

5. Run the website dev server with narew-cms dev ​

Run the website with a single command from your website project root:

sh
pnpm exec narew-cms dev

narew-cms dev:

  1. Resolves the CMS origin via --cms <url> (defaults to http://localhost:7700 or NAREW_CMS_ORIGIN).
  2. Fetches the preview session public key over HTTP from /v1/content-sessions/public-key (or uses NAREW_SESSION_PUBLIC_JWK if configured).
  3. Awaits CMS API liveness (/v1/health).
  4. Regenerates src/narew-content.ts in --mode remote-dev connecting the website to remote Cloudflare project resources.
  5. Launches wrangler dev on port 7730 (or --port <port>) with NAREW_CMS_ORIGIN and NAREW_SESSION_PUBLIC_JWK.

Open the CMS dashboard, select a record, and live preview will open your running website in the dashboard iframe with isolated replica edits and full media and cache integration.

Website queries and navigation ​

Call resolveContentEnv(request, env) from the generated module before content queries. Return its response directly; otherwise query site.env, pass site.selection to your publication filter, return site.finish(response) and route errors through site.fail(error). A site may have several D1 bindings, but a preview session covers one registered database: only that binding is replaced by the replica, and a mismatched registry fails closed. Never substitute public D1 when preview resolution or a replica query fails. The Worker example shows the full wiring; fetcher, isPublicResource and onSessionError are optional settings. The worker also re-exports the session class for the NAREW_SESSIONS Durable Object binding: export { ContentSession } from "@narew/content";

Publication and moderation are the website's responsibility. Public queries must always filter out unpublished records. In preview, allow only the authenticated selected record in addition to published records; do not simply remove the filter. The checked-in query example shows this for an integer primary key. Other keys, compound keys, related collections, publication schedules and moderation rules need equivalent site-specific predicates. Use selectedKey rather than a single selectedField when the collection key has more than one field.

The iframe preserves its session on same-origin links, forms, History API navigation and fetch. A site's own framework or JavaScript may use other navigation/data-loading mechanisms; those need integration and testing. Browser-loaded static assets without the selector remain public. If a browser omits Sec-Fetch-Dest, serve known static assets before preview resolution or use the isPublicResource option to allow only known public GET/HEAD assets. Never classify content endpoints as public resources.

Limits and failure behavior ​

  • One snapshot is limited to 2,000,000 bytes, 10,000 rows, 256 schema objects, 2,048 columns, and a 1,900,000-byte row. Individual replica queries are limited to 1,000 result rows, 2,000,000 result bytes, 2,000,000 bound-parameter bytes, and 250,000 scanned rows.
  • A session lasts at most 30 minutes. The dashboard attempts to renew it using the server's expiry and the last verified iframe location. If the location cannot be verified, it reports expiry instead; retrying issues a fresh session against the current source, and unsaved edits stay in the editor.
  • Triggers on an edited table, unsupported schemas, unsupported database operations or invalid drafts fail rather than producing a partial preview. The replica is read-only to website code; batch, exec, dump, transactions and writes are not supported.
  • Source data is fingerprinted again for preview requests and queries. A changed source invalidates the session: retry to start a fresh one. This provides detection, not a lock against concurrent source writes, and repeated full snapshots can be expensive. Measure against your data and Workers limits.
  • The server checks the editor's session and permissions online; revoked, expired, mismatched, or unavailable authorization fails closed. Preview requires the CMS to be reachable. Public requests do not.

The preview cookie is HttpOnly, Secure, SameSite=None and Partitioned; the session token is exchanged using the iframe handshake, not placed in the URL. Preview responses are private and non-cacheable. Review any additional CSP, service workers, CDN caching and external content in your own site. For application-owned caches, use the shared cache helper or createContentReader, which treats cache failures as best effort, or explicitly bypass both cache reads and writes during sessions.

Migrating from the preview API ​

The preview website integration was renamed to the neutral content API before release. There are no compatibility aliases; upgrading a site already wired to the old names requires these steps in order:

  1. Upgrade @narew/content and @narew/cli in the website workspace. A source upgrade alone changes nothing that is deployed.

  2. Run narew-cms content bind with the same binding artifact, public key and CMS origin. It appends a migration creating __narew_content_binding; apply it to the registered D1. The old __narew_preview_binding table becomes inert — leave it or drop it manually.

  3. Run narew-cms content env --mode <deployment|remote-dev> to generate src/narew-content.ts, replacing preview registry and src/preview-registry.ts. Import resolveContentEnv from the generated module and call it as resolveContentEnv(request, env).

  4. Rename the Worker variables: CMS_ORIGIN → NAREW_CMS_ORIGIN, PREVIEW_PUBLIC_JWK → NAREW_SESSION_PUBLIC_JWK, and the Durable Object binding PREVIEWS → NAREW_SESSIONS with class ContentSession.

  5. Append a migration renaming the Durable Object class and deploy it with the new code:

    jsonc
    {
    	"tag": "content-session-v1",
    	"renamed_classes": [{ "from": "PreviewReplica", "to": "ContentSession" }],
    }
  6. Old sessions, cookies and signed bindings are invalidated. New sessions use narew-content-binding signatures, /v1/content-sessions/* endpoints, /__narew/session/* protocol paths and __Host-narew-session-* cookies. Requests carrying the old indicators fail closed with a sanitized error.

  7. Non-Workers consumers that only verify the signed binding move to @narew/content/binding; the old @narew/content/preview entry point no longer exists.