Integrate BeechCMS with Astro
Build blazing fast, content-driven websites with Astro and BeechCMS using zero client-side JavaScript by default.
You are an expert full-stack developer integrating BeechCMS into a Astro 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 Astro, 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 an Astro app
Create a new Astro project using the official template:
npm create astro@latest my-astro-app -- --template minimal --typescript strict
cd my-astro-app3. Install the official client SDK
Install @beechcms/client in your Astro project:
$ pnpm add @beechcms/client4. Declare environment variables
Create a .env file in your Astro project root:
BEECH_API_URL=http://localhost:8789
BEECH_SECRET_KEY=beech_sk_dev
beech_sk_devis the local secret key every new project has in.dev.vars. Keep this variable server-only. In production, set these variables in your deployment environment.
5. Initialize the Beech client
Create src/lib/beech.ts to instantiate a typed server-side client module:
// src/lib/beech.ts
import { createBeechServerClient } from '@beechcms/client/server'
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 = createBeechServerClient<AppRegistry>({
baseUrl: import.meta.env.BEECH_API_URL || 'http://localhost:8789',
secretKey: import.meta.env.BEECH_SECRET_KEY!
})6. Query and render content
Replace src/pages/index.astro with an Astro component that queries BeechCMS at build time (or on demand in SSR mode) and renders articles:
---
// src/pages/index.astro
import { beech } from '../lib/beech'
import { renderRichText } from '@beechcms/client/richtext'
const result = await beech
.collection('articles')
.orderBy('created_at', 'desc')
.limit(10)
.list()
const articles = result.data ? result.data.data : []
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>BeechCMS + Astro</title>
</head>
<body style="font-family: sans-serif; max-width: 800px; margin: 0 auto; padding: 2rem;">
<h1>BeechCMS + Astro</h1>
{articles.length === 0 ? (
<p>No articles found. Plant your first article in the BeechCMS dashboard!</p>
) : (
<div style="display: grid; gap: 1.5rem;">
{articles.map((article) => (
<article style="border: 1px solid #e2e8f0; border-radius: 8px; padding: 1.25rem;">
{article.cover_image && (
<img src={article.cover_image} alt={article.title} style="max-width: 100%; border-radius: 4px;" />
)}
<h2 style="margin-top: 0.5rem;">{article.title}</h2>
<div set:html={renderRichText(article.body)} />
<a href={`/articles/${article.slug}`}>Read article →</a>
</article>
))}
</div>
)}
</body>
</html>Static Generation with getStaticPaths (Optional)
To statically generate detail pages for every published article, create src/pages/articles/[slug].astro:
---
// src/pages/articles/[slug].astro
import { beech, type Article } from '../../lib/beech'
import { renderRichText } from '@beechcms/client/richtext'
export async function getStaticPaths() {
const result = await beech.collection('articles').limit(100).list()
const articles = result.data ? result.data.data : []
return articles.map((article) => ({
params: { slug: article.slug },
props: { article }
}))
}
const { article } = Astro.props as { article: Article }
const bodyHtml = renderRichText(article.body)
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{article.title}</title>
</head>
<body style="font-family: sans-serif; max-width: 700px; margin: 0 auto; padding: 2rem;">
<article>
<h1>{article.title}</h1>
{article.cover_image && (
<img src={article.cover_image} alt={article.title} style="max-width: 100%; border-radius: 6px;" />
)}
<div set:html={bodyHtml} />
</article>
</body>
</html>7. Start the app
Run the Astro development server:
npm run devOpen http://localhost:4321 in your browser. You will see your BeechCMS content rendered on screen with zero client-side JavaScript.
Production requirements
Before deploying to production:
- Configure Seed Permissions: Ensure your Seed has
allowPublicRead: trueenabled in the admin dashboard so public visitors can fetch published content. - Production API URL: Point
BEECH_API_URLto your production Cloudflare Worker URL (https://api.yourdomain.com). - Production Secret Key: Set
BEECH_SECRET_KEYto the production secret key, the generatedbeech_sk_live_…value you stored on the BeechCMS Worker withnpx wrangler secret put BEECH_SECRET_KEY. The API refusesbeech_sk_devoutside development. - Zero-JS by Default: Astro executes data fetching on the server/build isolate and ships zero client-side JavaScript by default, making it ideal for content-heavy sites.
Cloudflare Edge Deployment
When deploying Astro to Cloudflare:
- Zero-Cost Static Mode (
output: 'static'): By default, Astro compiles into pure static HTML and assets (dist/). Deploy directly to Cloudflare Pages with zero worker execution costs and instant global CDN delivery. - On-Demand Edge SSR (
output: 'server'): If you need on-demand rendering or dynamic auth, add the official Cloudflare adapter:bashnpx astro add cloudflare - Accessing Edge Geolocation Context: In SSR mode, access Cloudflare's visitor context (country, city, ASN) directly inside frontmatter via
Astro.locals:astro--- const country = Astro.locals.runtime?.cf?.country || 'US' ---
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.