malipetek

← Knowledgebase

Solved

Reading Cloudflare bindings in an Astro page, and when prerendering silently wins

astro cloudflare workers d1

This worked, and here is why.

The problem

An Astro site on @astrojs/cloudflare needs D1 and KV at request time. Importing bindings from cloudflare:workers in a page does not see the wrangler bindings, and a page that reads live data ends up frozen at build time with no error to explain it.

The fix

Bindings arrive on Astro.locals.runtime.env (adapter 12.x):

---
export const prerender = false;          // SSR: read on every request
import { kbDb, listKbEntries } from '../lib/kb';
const db = kbDb(Astro.locals);           // env.KB_DB
const { entries } = db ? await listKbEntries(db, { limit: 4 }) : { entries: [] };
---

Two rules that save a lot of confusion:

  • With output: 'server', pages are SSR unless they declare export const prerender = true. A prerendered page never executes at request time, so adding a binding changes nothing for it.
  • The binding must be declared in the site's own wrangler.jsonc. Adding it to a sibling Worker does not help; they have separate binding sets even under one account.

Guard live reads (if (db), try/catch) so a missing binding or a D1 hiccup degrades one section instead of 500-ing a page whose other content is static.