Skip to content

Configuration

Temp edited this page Jan 7, 2026 · 4 revisions

Configuration

Complete guide to configuring D1 Database Manager for different environments.

Environment Variables

D1 Manager uses environment variables for configuration. There are two types:

  1. Frontend Environment Variables - Stored in .env (Vite)
  2. Worker Secrets - Stored securely in Cloudflare Workers

Frontend Configuration

.env File

Create a .env file in the project root:

cp .env.example .env

Frontend Variables

Variable Description Default Required
VITE_WORKER_API Worker API URL window.location.origin No

VITE_WORKER_API

Specifies where the frontend sends API requests.

Local Development:

VITE_WORKER_API=http://localhost:8787

Production:

# Comment out or remove this line
# VITE_WORKER_API=http://localhost:8787

When undefined, the app uses window.location.origin (same domain as the frontend).

Worker Configuration

Wrangler Configuration Files

D1 Manager uses two Wrangler config files:

File Purpose
wrangler.toml Production configuration (committed to repo)
wrangler.dev.toml Local development configuration

wrangler.toml (Production)

name = "d1-manager"
main = "worker/index.ts"
compatibility_date = "2024-10-15"
workers_dev = false

# Asset configuration for serving frontend
[assets]
directory = "dist"
binding = "ASSETS"

# Custom domain routing (optional)
[[routes]]
pattern = "d1.yourdomain.com/*"
zone_name = "yourdomain.com"

# D1 database binding for metadata
[[d1_databases]]
binding = "DB"
database_name = "d1-manager-metadata"
database_id = "your-database-id-here"

# R2 Backup Bucket (optional - enables cloud backups)
[[r2_buckets]]
binding = "BACKUP_BUCKET"
bucket_name = "d1-manager-backups"

# Durable Objects for async backup processing
[[durable_objects.bindings]]
name = "BACKUP_DO"
class_name = "BackupDO"
script_name = "d1-manager"

[[migrations]]
tag = "v1"
new_classes = ["BackupDO"]

# Observability
[observability]
enabled = true

Configuration Options

name - Worker name (must be unique in your account)

name = "d1-manager"

main - Entry point file

main = "worker/index.ts"

compatibility_date - Cloudflare Workers runtime version

compatibility_date = "2024-10-15"

workers_dev - Enable/disable workers.dev subdomain

workers_dev = false  # Disable for production
workers_dev = true   # Enable for testing

assets - Frontend asset serving

[assets]
directory = "dist"      # Build output directory
binding = "ASSETS"      # Binding name in Worker code

routes - Custom domain routing

[[routes]]
pattern = "d1.yourdomain.com/*"     # URL pattern
zone_name = "yourdomain.com"         # Cloudflare zone

Multiple routes can be defined for multiple domains.

d1_databases - D1 database bindings

[[d1_databases]]
binding = "DB"                                    # Binding name
database_name = "d1-manager-metadata"             # Database name
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx"  # Database UUID

r2_buckets - R2 storage for backups (optional)

[[r2_buckets]]
binding = "BACKUP_BUCKET"                         # Binding name
bucket_name = "d1-manager-backups"                # R2 bucket name

durable_objects - Async backup processing (required if using R2)

[[durable_objects.bindings]]
name = "BACKUP_DO"
class_name = "BackupDO"
script_name = "d1-manager"

[[migrations]]
tag = "v1"
new_classes = ["BackupDO"]

observability - Logging and monitoring

[observability]
enabled = true  # Enable Worker analytics

wrangler.dev.toml (Local Development)

name = "d1-manager-dev"
main = "worker/index.ts"
compatibility_date = "2024-10-15"

# No asset binding needed for local dev (Vite serves frontend)
# No D1 binding needed (uses mock data)

This simplified config is used for local development with mock data.

Worker Secrets

Secrets are encrypted environment variables stored securely in Cloudflare.

Required Secrets (Production)

Secret Description How to Get
ACCOUNT_ID Cloudflare Account ID Dashboard URL
API_KEY Cloudflare API Token API Tokens page
TEAM_DOMAIN Cloudflare Access Team Domain Zero Trust dashboard
POLICY_AUD Application Audience Tag Access Application settings

Setting Secrets

Use the Wrangler CLI to set secrets:

# Set each secret (you'll be prompted to enter the value)
npx wrangler secret put ACCOUNT_ID
npx wrangler secret put API_KEY
npx wrangler secret put TEAM_DOMAIN
npx wrangler secret put POLICY_AUD

Getting Secret Values

ACCOUNT_ID

Found in the Cloudflare dashboard URL:

https://dash.cloudflare.com/YOUR_ACCOUNT_ID
                           ^^^^^^^^^^^^^^^^

Or go to: Workers & Pages β†’ Overview β†’ Account ID

API_KEY

  1. Go to Cloudflare Dashboard
  2. Click your profile β†’ API Tokens
  3. Click Create Token β†’ Create Custom Token
  4. Configure permissions:
    • Account β†’ D1 β†’ Edit
  5. Copy the token immediately (shown only once)

Important: Use an API Token, not the Global API Key.

TEAM_DOMAIN

Your Cloudflare Zero Trust team domain:

https://yourteam.cloudflareaccess.com
  1. Go to Cloudflare Zero Trust
  2. Settings β†’ General
  3. Copy your Team Domain

POLICY_AUD

Application Audience Tag from Cloudflare Access:

  1. Go to Zero Trust β†’ Access β†’ Applications
  2. Select your D1 Manager application
  3. Copy the Application Audience (AUD) tag

Example:

a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6

Listing Secrets

Check which secrets are set:

npx wrangler secret list

Deleting Secrets

Remove a secret:

npx wrangler secret delete SECRET_NAME

Database Configuration

Create Metadata Database

The Worker uses a D1 database to store query history and saved queries:

# Create the database
npx wrangler d1 create d1-manager-metadata

# Initialize the schema
npx wrangler d1 execute d1-manager-metadata --remote --file=worker/schema.sql

Update wrangler.toml

After creating the database, update wrangler.toml:

[[d1_databases]]
binding = "DB"
database_name = "d1-manager-metadata"
database_id = "YOUR_DATABASE_ID_FROM_CREATE_COMMAND"

Protected System Database

The d1-manager-metadata database is automatically protected from:

  • Deletion
  • Renaming
  • Export
  • Appearing in the database list

This prevents accidental deletion of application data.

CORS Configuration

CORS (Cross-Origin Resource Sharing) is configured in the Worker.

Development CORS

In worker/utils/cors.ts, localhost is automatically allowed:

const allowedOrigins = [
  'http://localhost:5173',  // Vite dev server
  'http://localhost:8787',  // Wrangler dev
];

Production CORS

For production, the Worker automatically allows the deployed domain:

// Uses request origin if it matches the worker domain
if (origin && origin === workerOrigin) {
  return origin;
}

Advanced Configuration

Custom Port for Local Development

Frontend (Vite)

npm run dev -- --port 3000

Update .env:

VITE_WORKER_API=http://localhost:8787

Worker (Wrangler)

npx wrangler dev --config wrangler.dev.toml --local --port 8788

Update .env:

VITE_WORKER_API=http://localhost:8788

Multiple Environments

Create separate configs for different environments:

wrangler.staging.toml
wrangler.production.toml

Deploy to specific environment:

npx wrangler deploy --config wrangler.staging.toml

Build Configuration

Vite Configuration (vite.config.ts)

export default defineConfig({
  plugins: [react()],
  server: {
    port: 5173,
    strictPort: false,
  },
  build: {
    outDir: 'dist',
    sourcemap: true,
  },
});

TypeScript Configuration

tsconfig.json - Main TypeScript config tsconfig.app.json - Frontend-specific config tsconfig.node.json - Node.js-specific config

Asset Caching

Configure asset caching in wrangler.toml:

[assets]
directory = "dist"
binding = "ASSETS"

# Optional: Configure caching
[assets.cache]
max_age = 31536000  # 1 year for static assets

Configuration Validation

Check Configuration

# Validate wrangler.toml
npx wrangler whoami

# Test local configuration
npx wrangler dev --config wrangler.dev.toml --local

# Test production configuration
npx wrangler deploy --dry-run

Common Configuration Issues

Issue: "Failed to list databases"

Cause: Missing or incorrect ACCOUNT_ID or API_KEY

Fix:

npx wrangler secret list  # Check secrets are set
npx wrangler secret put ACCOUNT_ID
npx wrangler secret put API_KEY

Issue: "Authentication error"

Cause: Incorrect TEAM_DOMAIN or POLICY_AUD

Fix:

npx wrangler secret put TEAM_DOMAIN
npx wrangler secret put POLICY_AUD

Issue: "Mock data in production"

Cause: VITE_WORKER_API is set to localhost

Fix: Remove or comment out in .env:

# VITE_WORKER_API=http://localhost:8787

Then rebuild:

npm run build
npx wrangler deploy

Environment-Specific Tips

Local Development

  • Keep VITE_WORKER_API=http://localhost:8787 in .env
  • Use wrangler.dev.toml for Worker
  • No secrets required
  • Mock data automatically enabled

Production

  • Remove or comment out VITE_WORKER_API
  • Use wrangler.toml (not tracked in git)
  • Set all required secrets
  • Real Cloudflare D1 data

Staging/Testing

  • Create wrangler.staging.toml
  • Use separate D1 database for staging
  • Set separate secrets with --env staging
  • Deploy with --config wrangler.staging.toml

Security Best Practices

  1. Never commit secrets - Keep .env and wrangler.toml in .gitignore
  2. Use API Tokens - Not Global API Keys
  3. Minimal Permissions - Grant only D1 Edit permission
  4. Rotate Regularly - Change API tokens periodically
  5. Audit Access - Review Cloudflare Access logs

Next Steps


Need Help? See Troubleshooting or open an issue.

Clone this wiki locally