Integrate BeechCMS with React
Connect your React single-page application (Vite, Next.js client components, or SPA) to BeechCMS using the official @beechcms/client SDK.
You are an expert full-stack developer integrating BeechCMS into a React application.
BeechCMS is an edge-native headless CMS built on Cloudflare Workers, D1, and R2.
Documentation Base: https://fdemusso.github.io/BeechCMS/
Official Client SDK: @beechcms/client
Forms SDK: @beechcms/forms-react
Search Client: @beechcms/search-client
Key Architecture Guidelines:
- Edge Native: Sub-millisecond latency on Cloudflare edge.
- Client SDK: Use createBeechBrowserClient / createBeechServerClient from '@beechcms/client/browser' or '@beechcms/client/server' with baseUrl and publishableKey (browser) or secretKey (server).
- Content Querying: Every read starts at beech.collection('seedSlug') and returns a fluent query builder. Chain .where({ field: value }) or .where({ field: { gte: 10 } }), .logic('AND' | 'OR'), .orderBy('created_at', 'desc'), .search(term), .select([...]), .include([...]), .limit(n), .page(n), then terminate with .list() or .first(). Example: beech.collection('seedSlug').orderBy('created_at', 'desc').limit(10).list(), or beech.collection('seedSlug').where({ slug }).first().
- Relations: .include(['author']) expands related entries in the same request under entry._includes.author (depth 1, max 3 branches). .whereRelation('author', { where: { name: 'Jane' } }) filters through the relation target server-side. Never issue N+1 follow-up requests.
- Result Unwrapping: Extract records from result.data.data and handle errors via result.error. .first() returns a 404 BeechProblem when nothing matches — it does not return null.
- Types: Generate the seed registry with 'npx beech types generate' and pass it as the client generic: createBeechBrowserClient<BeechDatabase>({ ... }).
- RichText: Render TipTap body AST via renderRichText(post.body) from '@beechcms/client/richtext'.
- Content Models: Seeds define schemas, Branches define fields, Fruits represent content items.
- Dual-Table Mirror Staging: Drafts stay isolated in draft staging tables and promote atomically to production.
Generate the integration code following strict TypeScript typing, clean error handling, and modern edge-rendering patterns.1. Set up your BeechCMS backend & sample Seed
Before querying data in React, ensure you have a running BeechCMS instance with sample content:
- Start BeechCMS: If running locally, start your backend via
pnpm run dev(running onhttp://localhost:8789), or use your deployed Cloudflare Worker URL. - Verify or Create the Seed: In your BeechCMS admin dashboard (
/admin), verify you have anarticlesSeed with:- Branches:
title(Text) andbody(Rich Text). Do not add aslugbranch:slugis a reserved system column that BeechCMS fills from the title on every entry (hello-beechcms); theslugfield used below is that column. - Permissions: Ensure Allow Public Read (
allowPublicRead) is checked so public requests can fetch content without admin secrets.
- Branches:
- Publish a Fruit (Record): Create at least one article and click Publish.
2. Create a React app
Create a new React project with TypeScript using the Vite template:
npm create vite@latest my-react-app -- --template react-ts
cd my-react-app3. Install the official client SDK
Install @beechcms/client in your React project:
$ pnpm add @beechcms/client4. Declare environment variables
Create a .env.local file in your React project root:
VITE_BEECH_API_URL=http://localhost:8789
VITE_BEECH_PUBLISHABLE_KEY=beech_pk_dev
beech_pk_devis the publishable key every new project has inwrangler.jsonc. It is read-only and safe in the bundle.
5. Initialize the Beech client
Create src/lib/beech.ts to instantiate the browser client with strong TypeScript typing:
// src/lib/beech.ts
import { createBeechBrowserClient } from '@beechcms/client/browser'
export interface Article {
id: string
title: string
slug: string
cover_image?: string
body: string | Record<string, unknown>
created_at: number
updated_at: number
}
export interface AppRegistry {
articles: Article
}
export const beech = createBeechBrowserClient<AppRegistry>({
baseUrl: import.meta.env.VITE_BEECH_API_URL || 'http://localhost:8789',
publishableKey: import.meta.env.VITE_BEECH_PUBLISHABLE_KEY!
})6. Query and render content
Replace the contents of src/App.tsx with a complete component that fetches articles and renders TipTap rich text via renderRichText:
// src/App.tsx
import { useEffect, useState } from 'react'
import { beech, type Article } from './lib/beech'
import { renderRichText } from '@beechcms/client/richtext'
export default function App() {
const [articles, setArticles] = useState<Article[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
async function loadArticles() {
try {
setLoading(true)
const result = await beech
.collection('articles')
.orderBy('created_at', 'desc')
.limit(10)
.list()
if (result.error) {
setError(result.error.detail || 'Failed to load articles')
} else if (result.data) {
setArticles(result.data.data)
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Network error')
} finally {
setLoading(false)
}
}
loadArticles()
}, [])
if (loading) {
return <p style={{ padding: '2rem' }}>Loading articles...</p>
}
if (error) {
return <p style={{ padding: '2rem', color: '#ef4444' }}>Error: {error}</p>
}
return (
<main style={{ maxWidth: '800px', margin: '0 auto', padding: '2rem', fontFamily: 'sans-serif' }}>
<h1>BeechCMS + React</h1>
{articles.length === 0 ? (
<p>No articles found. Create your first fruit in the BeechCMS dashboard!</p>
) : (
<div style={{ display: 'grid', gap: '1.5rem' }}>
{articles.map((article) => (
<article
key={article.id}
style={{
border: '1px solid #e2e8f0',
borderRadius: '8px',
padding: '1.25rem'
}}
>
<h2 style={{ marginTop: 0 }}>{article.title}</h2>
<div
dangerouslySetInnerHTML={{ __html: renderRichText(article.body) }}
/>
</article>
))}
</div>
)}
</main>
)
}7. Start the app
Run the Vite development server:
npm run devOpen http://localhost:5173 in your browser. You will see your BeechCMS articles rendered directly on screen.
Production requirements
The quickstart procedure in this guide optimizes for getting you to a working app quickly. Before deploying to production:
- Configure Seed Permissions: Verify that your Seed has
allowPublicRead: trueenabled in the admin dashboard so public visitors can fetch published content. - Production API URL: Point
VITE_BEECH_API_URLto your production Cloudflare Worker URL (https://api.yourdomain.com). - Production Publishable Key: Set
VITE_BEECH_PUBLISHABLE_KEYto theBEECH_PUBLISHABLE_KEYvalue in the BeechCMS Worker'swrangler.jsoncvars. It is read-only and public by design. - Client Security: Notice that
@beechcms/client/browseris physically read-only. Mutation methods (create,update,delete) are omitted from browser bundles to keep your administrative write keys secure.
Cloudflare Edge Deployment
When deploying your React frontend to Cloudflare Pages:
- Zero-Cost Static Hosting: Pure React SPAs compile into static assets (
dist/). Connect your repository to Cloudflare Pages, set the build command tonpm run build, and output directory todist. Cloudflare serves it globally across 300+ edge locations with unlimited bandwidth and zero compute costs. - SPA Routing Fallback (
_redirects): To prevent 404 errors when visitors refresh deep URLs (e.g.,/articles/spring-release), create apublic/_redirectsfile:text/* /index.html 200 - CORS & Same-Zone Routing:
- In your BeechCMS Worker configuration, add your Pages domain (e.g.
https://my-app.pages.dev) to theCORS_ORIGINSenvironment variable. - Edge Pro-Tip (Zero CORS Latency): On a custom domain managed by Cloudflare, route
/api/*to your BeechCMS Worker and/*to your React Pages site within the same zone. Serving both under the same origin completely eliminates CORS preflight latency.
- In your BeechCMS Worker configuration, add your Pages domain (e.g.
Next steps
- 5-Minute First Project Tutorial: Follow a step-by-step tutorial covering project scaffolding, database bootstrap, visual modeling, and deployment.
- Client SDK Reference: Explore advanced querying, filtering, and pagination parameters.
- Public API Reference: Understand Edge REST endpoints, caching headers, and RFC 7807 error responses.
- Forms SDK (@beechcms/forms-react): Capture user submissions and feedback with zero secrets and built-in bot defense.