LogoNEXTDEVKIT Docs

Cloudflare D1 Database

Complete Cloudflare D1 setup guide for NEXTDEVKIT edge deployments with D1 and KV configuration.

Cloudflare D1 is the default database for NEXTDEVKIT's Cloudflare Workers deployment, offering global edge database with low latency and automatic replication.

🚀 Why Cloudflare D1?

Cloudflare D1 is chosen for Cloudflare Workers deployment because:

  • ⚡ Edge performance: Database runs at the edge, close to users
  • 🌍 Global replication: Automatic data replication worldwide
  • 🔧 SQLite compatibility: Familiar SQL syntax and operations
  • 💰 Cost-effective: Pay-per-use pricing model
  • 🔄 Serverless scaling: Automatic scaling with your Workers
  • 🛡️ Built-in security: Integrated with Cloudflare's security features

🏗️ Database Architecture

D1 + KV Storage Architecture

NEXTDEVKIT uses Cloudflare D1 for structured data and Cloudflare KV for caching:

ComponentNext.js App (Worker)Cloudflare D1 (Database)Cloudflare KV (Cache)
PurposeEdge ApplicationStructured Data StorageCaching Layer
FeaturesPagesUser dataCache data
API RoutesPaymentTemp data
MiddlewareSettings

🔧 Initial Setup

1. Create D1 Database

Create a new D1 database for your NEXTDEVKIT project:

# Create D1 database
pnpm wrangler d1 create prod-d1-tutorial

Expected Output:

   ✅ Successfully created DB 'prod-d1-tutorial' in region WEUR
   Created your new D1 database.

   {
     "d1_databases": [
       {
         "binding": "DB",
         "database_name": "prod-d1-tutorial",
         "database_id": "<unique-ID-for-your-database>"
       }
     ]
   }

2. Create KV Namespace

Create a KV namespace for caching and session storage:

# Create KV namespace
pnpm wrangler kv namespace create nextdevkit-cloudflare-template-kv

Expected Output:

🌀 Creating namespace with title "USERS_NOTIFICATION_CONFIG"
✨ Success!
Add the following to your configuration file in your kv_namespaces array:
{
  "kv_namespaces": [
    {
      "binding": "USERS_NOTIFICATION_CONFIG",
      "id": "<BINDING_ID>"
    }
  ]
}

3. Configure wrangler.jsonc

Update your wrangler.jsonc file with the database and KV configuration:

// wrangler.jsonc
{
  "name": "nextdevkit-cloudflare-template",
  "compatibility_flags": ["nodejs_compat"],
  
  // D1 Database Configuration
  "d1_databases": [
    {
      "binding": "NEXT_TAG_CACHE_D1",
      "database_name": "your-database-name",
      "database_id": "<unique-ID-for-your-database>",
      "migrations_dir": "drizzle"
    }
  ],
  
  // KV Namespace Configuration
  "kv_namespaces": [
    {
      "binding": "NEXT_INC_CACHE_KV",
      "id": "<unique-ID-for-your-namespace>"
    }
  ],
}

🔧 Local Development Setup

1. Create Local D1 Database

Initialize D1 database in local development environment:

# Create local D1 database
npx wrangler d1 execute your-database-name --local --command='SELECT 1'

🗄️ Database Schema Configuration

Schema Definition

D1 uses the same schema as PostgreSQL but with SQLite syntax:

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

export const user = sqliteTable("user", {
  id: text("id").primaryKey(),
  name: text("name").notNull(),
  email: text("email").notNull().unique(),
  emailVerified: integer("emailVerified", { mode: "timestamp" }),
  ...
});

Database Client Configuration

Configure D1 client for Cloudflare Workers:

import { drizzle } from 'drizzle-orm/d1';
import * as schema from './schema';

// For Cloudflare Workers
...

// For local development
...

🔄 Schema Migrations

Migration Configuration

Configure Drizzle for D1 migrations:

// drizzle.config.ts
import { defineConfig } from "drizzle-kit";

export default defineConfig({
  ...
});

Migration Commands

pnpm run db:generate
pnpm run db:migrate:dev
pnpm run db:migrate:prod

Studio

If you want to use the drizzle studio in the cloudflare d1 production environment, you can use the drizzle chrome extension to connect to the database.

🔍 Monitoring & Debugging

D1 Analytics

Monitor D1 performance in Cloudflare Dashboard:

  • Query execution times
  • Database size and usage
  • Error rates and types
  • Geographic performance metrics

KV Analytics

Monitor KV operations:

  • Read/write operations
  • Cache hit rates
  • Storage usage
  • Geographic distribution

🛠️ Troubleshooting

Common Issues

D1 Connection Errors:

  • Verify database ID in wrangler.jsonc
  • Check binding names match code usage
  • Ensure migrations are applied

KV Access Issues:

  • Verify KV namespace ID
  • Check binding configuration
  • Ensure proper permissions

Migration Failures:

  • Review SQLite syntax compatibility
  • Check for constraint violations
  • Verify schema changes are valid

🎯 Next Steps

Now that you understand the database architecture, dive into the specific setup for your chosen platform: