🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
CMS & Integrations••By Komal Nakrani

Astro Cloudflare D1 and KV: Bindings, Queries and Caching

Use Astro with Cloudflare D1 and KV: add the adapter, declare bindings in Wrangler, query D1 from endpoints and actions, cache reads in KV and type it all.

#Astro#Cloudflare D1#Cloudflare KV#Cloudflare Workers#Server Rendering

To use Cloudflare D1 from Astro, add the Cloudflare adapter with npx astro add cloudflare, declare a D1 database (and any KV namespaces) as bindings in your Wrangler config, then import env from cloudflare:workers in an on-demand route and call env.DB.prepare(sql).bind(...).all(). KV works the same way through env.CACHE.get() and env.CACHE.put(). Bindings are only available to code that runs on request, so every route that touches them needs export const prerender = false (or a server-first output).

This guide covers the setup, schema migrations, reading and writing D1 from endpoints, pages and Astro Actions, using KV as a cache and for flags, local development, and types.

Key Takeaways

  • D1 is SQLite with SQL queries and transactions; KV is a global key-value store tuned for fast, eventually consistent reads.
  • Declare both in wrangler.jsonc; the binding name (DB, CACHE) is the property you read on env.
  • Read bindings with import { env } from 'cloudflare:workers' inside routes that render on request.
  • Use wrangler d1 migrations for schema changes and apply them locally and remotely.
  • Put KV in front of slow or repeated D1 reads, with a short expirationTtl.

When D1 and KV make sense in an Astro project

Most Astro sites never need a database. Pages build to HTML, content lives in Markdown or a CMS, and forms go to a form service. D1 and KV start paying off when the site has to remember something between requests: newsletter signups, view counters, a waitlist, feature flags, short links, a small catalogue that changes during the day.

The two products solve different problems:

Cloudflare D1 Cloudflare KV
Data model SQLite tables, SQL queries Keys and values (strings, JSON, binary)
Consistency Strong for a single database Eventually consistent across locations
Best for Relational data, writes, filters and joins Read-heavy lookups, caches, config, flags
Writes Normal SQL inserts and updates Fine for occasional writes to a key, not for counters
Query style prepare().bind().all() get(), put(), delete(), list()

If you need to ask “all signups from last week”, use D1. If you need “the value for this key, fast, from anywhere”, use KV. Many projects use both: D1 as the source of truth and KV as a cache in front of it.

If you are still choosing a database, our comparison of Astro database options covers D1 next to Turso, Supabase, Neon and Astro DB.

Add the Cloudflare adapter

Bindings belong to a Worker, so the site needs server output on Cloudflare. Add the adapter:

# terminal
npx astro add cloudflare

This installs @astrojs/cloudflare and adds it to astro.config.mjs. Keep output at its default of 'static' if most pages are static; then opt individual routes into on-demand rendering:

// astro.config.mjs
import { defineConfig } from 'astro/config';
import cloudflare from '@astrojs/cloudflare';

export default defineConfig({
  site: 'https://www.example.com',
  adapter: cloudflare(),
});

Static pages still build to HTML and are served as assets. Only routes that export prerender = false run in the Worker. The adapters guide explains how this split works on each host, and the official Cloudflare adapter docs list every option.

Create the D1 database and KV namespace

Create both resources with Wrangler, Cloudflare’s CLI:

# terminal
npx wrangler d1 create astro-app
npx wrangler kv namespace create CACHE

Each command prints an ID. Add them to your Wrangler config as bindings. The adapter setup creates or updates this file; add the two binding blocks next to what is already there:

// wrangler.jsonc
{
  "name": "my-astro-site",
  "compatibility_date": "2026-10-01",
  "d1_databases": [
    {
      "binding": "DB",
      "database_name": "astro-app",
      "database_id": "paste-the-d1-id-here",
      "migrations_dir": "migrations"
    }
  ],
  "kv_namespaces": [
    { "binding": "CACHE", "id": "paste-the-kv-id-here" }
  ]
}

The binding value is the name your code uses. env.DB is the database and env.CACHE is the namespace. Pick short, uppercase names and keep them stable, because renaming a binding means changing every query.

Schema changes with D1 migrations

Treat the schema like code. Create a migration file:

# terminal
npx wrangler d1 migrations create astro-app create_signups

Wrangler writes a numbered SQL file in migrations/. Fill it in:

-- migrations/0001_create_signups.sql
CREATE TABLE signups (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  email TEXT NOT NULL UNIQUE,
  source TEXT,
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX idx_signups_created ON signups (created_at);

Apply it to the local copy first, then to the real database:

# terminal
npx wrangler d1 migrations apply astro-app --local
npx wrangler d1 migrations apply astro-app --remote

Wrangler records which migrations have run, so running the command again only applies new files. Commit the migrations/ folder with the code that depends on it.

Query D1 from an Astro endpoint

Endpoints are the plainest way in. Read env, prepare a statement, bind values and run it:

// src/pages/api/signups.ts
import type { APIRoute } from 'astro';
import { env } from 'cloudflare:workers';

export const prerender = false;

export const GET: APIRoute = async () => {
  const { results } = await env.DB.prepare(
    'SELECT email, created_at FROM signups ORDER BY created_at DESC LIMIT ?'
  )
    .bind(20)
    .all();

  return Response.json(results);
};

Always pass user input through .bind(). The ? placeholders are filled safely by D1, which rules out SQL injection from string concatenation. The statement methods you will use most:

  • .all() returns every row in results, plus meta with timing and row counts.
  • .first() returns the first row or null. Pass a column name to get one value: .first('total').
  • .run() executes a write and returns meta, including changes and last_row_id.
  • env.DB.batch([stmt1, stmt2]) runs several statements in one round trip, as a transaction.

Read D1 in a page

A page can query in its frontmatter, as long as it renders on request:

---
// src/pages/admin/signups.astro
import { env } from 'cloudflare:workers';

export const prerender = false;

const total = await env.DB.prepare('SELECT COUNT(*) AS total FROM signups').first('total');
const { results } = await env.DB.prepare(
  'SELECT email, source, created_at FROM signups ORDER BY created_at DESC LIMIT 50'
).all();
---
<h1>Signups ({total})</h1>
<table>
  <thead><tr><th>Email</th><th>Source</th><th>Date</th></tr></thead>
  <tbody>
    {results.map((row) => (
      <tr><td>{row.email}</td><td>{row.source}</td><td>{row.created_at}</td></tr>
    ))}
  </tbody>
</table>

An admin page like this needs protection. Put it behind Cloudflare Access, or check a session or header in middleware before the page renders.

Write to D1 from an Astro Action

For forms, an Astro Action gives you validation and typed results with less code than a hand-written endpoint. The handler runs in the Worker, so it can use the same env import:

// src/actions/index.ts
import { defineAction, ActionError } from 'astro:actions';
import { z } from 'astro/zod';
import { env } from 'cloudflare:workers';

export const server = {
  signup: defineAction({
    accept: 'form',
    input: z.object({
      email: z.email(),
      source: z.string().max(40).optional(),
    }),
    handler: async ({ email, source }) => {
      const result = await env.DB.prepare(
        'INSERT INTO signups (email, source) VALUES (?, ?) ON CONFLICT (email) DO NOTHING'
      )
        .bind(email.toLowerCase(), source ?? null)
        .run();

      if (!result.success) {
        throw new ActionError({ code: 'INTERNAL_SERVER_ERROR', message: 'Could not save signup' });
      }
      return { added: result.meta.changes === 1 };
    },
  }),
};

ON CONFLICT DO NOTHING makes a repeat signup harmless, and meta.changes tells you whether the row was new. The Astro Actions guide covers the form side: action={actions.signup}, reading the result and showing errors.

Use KV as a cache in front of D1

KV reads are fast everywhere, which makes it a good cache for queries many visitors trigger. Check KV first, fall back to D1 and store the answer with an expiry:

// src/lib/popular.ts
import { env } from 'cloudflare:workers';

type Popular = { slug: string; views: number }[];

export async function getPopular(): Promise<Popular> {
  const cached = await env.CACHE.get<Popular>('popular:v1', 'json');
  if (cached) return cached;

  const { results } = await env.DB.prepare(
    'SELECT slug, views FROM page_views ORDER BY views DESC LIMIT 10'
  ).all<{ slug: string; views: number }>();

  await env.CACHE.put('popular:v1', JSON.stringify(results), { expirationTtl: 300 });
  return results;
}

A few KV habits keep this predictable:

  1. Version your keys (popular:v1). When the shape changes, bump the version instead of hunting for stale entries.
  2. Use expirationTtl for caches. The minimum is 60 seconds.
  3. Expect propagation delay. A write is visible right away where it happened, but other locations can serve the old value for up to about a minute. Don’t use KV for counters or anything that must read its own writes globally.
  4. Use list({ prefix }) to find related keys, for example every flag: entry.

KV also works well for feature flags and redirects that editors change without a deploy: store flag:new-pricing as "on" and read it in middleware.

KV for Astro sessions

Astro sessions need a storage driver, and on Cloudflare the adapter uses KV by default. Add a KV namespace with the binding name the adapter expects (check the adapter docs for the current default) and Astro.session stores its data there, with only the session ID in a cookie. Our Astro sessions guide covers drivers and the session API.

Types for env

Without types, env.DB is any. Generate them from your Wrangler config:

# terminal
npx wrangler types

This writes worker-configuration.d.ts with an Env interface that includes DB: D1Database and CACHE: KVNamespace. Rerun it whenever you add or rename a binding, and include the file in tsconfig.json if your editor doesn’t pick it up. You can also type query rows with a generic, as in .all<{ slug: string; views: number }>() above.

Local development and deploys

astro dev with the Cloudflare adapter runs your server code against local copies of your bindings, so env.DB points at a local SQLite file and env.CACHE at a local store. Seed local data with npx wrangler d1 execute astro-app --local --file=./seed.sql. Remote data stays untouched until you pass --remote.

To deploy, build and let Wrangler upload the result, or connect the repository in the Cloudflare dashboard. The Cloudflare deploy docs cover the static side of a Komal theme, and the D1 documentation and KV documentation cover limits and pricing for each product.

Common mistakes

  • Querying in a prerendered page. Bindings exist at request time. If a page builds to HTML, it can’t read live D1 data. Add export const prerender = false.
  • String-building SQL. Always use ? and .bind().
  • Counters in KV. Concurrent writes overwrite each other. Use D1 with UPDATE page_views SET views = views + 1 WHERE slug = ?.
  • Forgetting the remote migration. The local database works, production throws “no such table”. Run migrations apply --remote as part of the deploy.
  • Leaking admin pages. Any on-demand route is public unless you protect it.

Komal themes build to static files and don’t ship an adapter, which keeps hosting simple. If you start from one of our Astro themes and later need signups or counters, the adapter and a few on-demand routes are all you add.

FAQ

Can Astro use Cloudflare D1 on a static site?

Only for routes that render on request. Add the Cloudflare adapter and export prerender = false from the routes that query D1. The rest of the site can stay static and is served as plain assets.

How do I access Cloudflare bindings in Astro?

Declare them in wrangler.jsonc, then import { env } from 'cloudflare:workers' in server code and read the binding by name, such as env.DB or env.CACHE. This works in endpoints, on-demand pages, middleware and Astro Actions.

Should I use D1 or KV for my Astro site?

Use D1 when you need SQL, filters, joins or reliable writes, such as signups or orders. Use KV for fast global reads of values that change rarely, such as caches, feature flags and redirects.

Does Cloudflare D1 work in astro dev?

Yes. With the Cloudflare adapter, astro dev uses a local copy of each binding. Apply migrations with --local and seed it with wrangler d1 execute --local before testing.

Is Cloudflare KV consistent enough for counters?

No. KV is eventually consistent and concurrent writes to one key can overwrite each other. Store counters in D1 and increment them with an UPDATE statement.