Skip to content

Connect a Worker to Cloudflare D1

Bind a D1 database to your Cloudflare Worker, define a SQLite schema with Drizzle, and verify the connection.

Cloudflare D1 is a serverless relational database that uses SQLite and integrates with Cloudflare Workers. Choose it for a Worker-backed app that needs persistent records without a separate Postgres service. Your Worker needs a binding to the actual D1 database. Selecting D1 in Cloud Studio doesn’t supply that binding.

Bind your project’s database

Create a D1 database

Create the database in Cloudflare for the application you plan to deploy. Keep its name and ID handy so you can distinguish it from other D1 databases in your account.

Bind it to the Worker

Add the D1 binding to the Worker’s configuration. Use the same binding name in your code and in the configuration for the environment you’re testing. A binding gives the Worker access to D1 without putting a database connection string in the frontend.

Apply the schema and check a query

Run the SQLite migration against the database the Worker binding points to. Then run a query from the Worker to confirm it can reach the database and that the expected table exists.

Define the schema with Drizzle

Use Drizzle’s SQLite schema helpers for typed queries against D1. This example stores prices as integer cents and maps the integer timestamp to a date in TypeScript.

import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";

export const products = sqliteTable("products", {
  id: text("id").primaryKey(),
  name: text("name").notNull(),
  priceInCents: integer("price_in_cents").notNull(),
  createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
});

The TypeScript definition describes the table for your queries. Apply a migration before using it to read or write data. If a query reports a missing table, check both the applied migrations and the target binding before changing the query. A migration applied locally doesn’t change the remote database.

Use SQLite features

Use joins to read related records, indexes for columns your queries filter on, and SQLite JSON operators when a record contains JSON. When multiple statements need to succeed or fail together, use D1’s transactional batch API. For a read-heavy app, evaluate read replication against your own workload rather than assuming every query runs near the user.

The D1 binding belongs to the Worker runtime. A working browser preview doesn’t prove that the deployed Worker has the right binding or that its D1 database has the expected schema.

Next

Was this page helpful?