To get started with Cloudflare Workers and bknd you can either install the package manually, and follow the descriptions below, or use the CLI starter:
Now in order to also server the static admin files, you have to modify the wrangler.toml to include the static assets. You can do so by either serving the static using the new Assets feature, or the deprecated Workers Site.
D1 now supports to enable global read replication. This allows to reduce latency by reading from the closest region. In order for this to work, D1 has to be started from a bookmark. You can enable this behavior on bknd by setting the d1.session property:
src/index.ts
import { serve } from "bknd/adapter/cloudflare";export default serve({ // ... d1: { // enables D1 sessions session: true, // (optional) restrict the transport, options: "header" | "cookie" // if not specified, it supports both transport: "cookie", // (optional) choose session constraint if not bookmark present // options: "first-primary" | "first-unconstrained" first: "first-primary", },});
If bknd is used in a stateful user context (like in a browser), it'll automatically send the session cookie to the server to set the correct bookmark. If you need to manually set the bookmark, you can do so by setting the x-cf-d1-session header:
The Cloudflare Vite Plugin allows to use Vite with Miniflare to emulate the Cloudflare Workers runtime. This is great, however, unenv disables any Node.js APIs that aren't supported, including the fs module. If you want to use plugins such as syncTypes, this will cause issues.
To fix this, bknd exports a Vite plugin that provides filesystem access during development. You can use it by adding the following to your vite.config.ts file:
The bknd CLI does not automatically have access to the Cloudflare bindings. We need to manually proxy them to the CLI by using the withPlatformProxy helper function:
config.ts now holds the configuration, and can safely be imported in your app. Since the CLI looks for a bknd.config.ts file by default, we change it to wrap the configuration from config.ts in the withPlatformProxy helper function.
bknd.config.ts
import { withPlatformProxy } from "bknd/adapter/cloudflare/proxy";import config from "./config";export default withPlatformProxy(config);
As an additional safe guard, you have to set a PROXY environment variable to 1 to enable the proxy.