# Configuration Guide

Complete reference for all configuration options when deploying Astro to Cloudflare Workers.

## Table of Contents

1. [wrangler.jsonc Reference](#wranglerjsonc-reference)
2. [Astro Configuration](#astro-configuration)
3. [Environment-Specific Configuration](#environment-specific-configuration)
4. [Bindings Configuration](#bindings-configuration)
5. [Advanced Options](#advanced-options)

---

## wrangler.jsonc Reference

### Core Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | Yes | Worker/Project name |
| `compatibility_date` | string (YYYY-MM-DD) | Yes | Runtime API version |
| `$schema` | string | No | Path to JSON schema for validation |
| `main` | string | No | Entry point file (auto-detected for Astro) |
| `account_id` | string | No | Cloudflare account ID |

### Assets Configuration

```jsonc
{
  "assets": {
    "directory": "./dist",
    "binding": "ASSETS",
    "html_handling": "force-trailing-slash",
    "not_found_handling": "404-page"
  }
}
```

| Option | Values | Default | Description |
|--------|--------|---------|-------------|
| `directory` | path | `"./dist"` | Build output directory |
| `binding` | string | `"ASSETS"` | Name to access assets in code |
| `html_handling` | `"none"`, `"force-trailing-slash"`, `"strip-trailing-slash"` | `"none"` | URL handling behavior |
| `not_found_handling` | `"none"`, `"404-page"`, `"spa-fallback"` | `"none"` | 404 error behavior |

### Compatibility Flags

```jsonc
{
  "compatibility_flags": ["nodejs_compat", "disable_nodejs_process_v2"]
}
```

| Flag | Purpose |
|------|---------|
| `nodejs_compat` | Enable Node.js APIs in Workers |
| `disable_nodejs_process_v2` | Use legacy process global (for some packages) |

---

## Astro Configuration

### Adapter Options

```javascript
// astro.config.mjs
import cloudflare from '@astrojs/cloudflare';

export default defineConfig({
  adapter: cloudflare({
    // Mode: how routes are deployed
    mode: 'directory',      // 'directory' (default) or 'standalone'

    // Image service handling
    imageService: 'passthrough',  // 'passthrough' (default) or 'compile'

    // Platform proxy for local development
    platformProxy: {
      enabled: true,
      configPath: './wrangler.jsonc',
      persist: {
        path: './.cache/wrangler/v3',
      },
    },
  }),
});
```

### Mode Comparison

| Mode | Description | Use Case |
|------|-------------|----------|
| `directory` | Separate function per route | Most projects, better caching |
| `standalone` | Single worker for all routes | Simple apps, shared state |

### Image Service Options

| Option | Description |
|--------|-------------|
| `passthrough` | Images pass through unchanged (default) |
| `compile` | Images optimized at build time using Sharp |

---

## Environment-Specific Configuration

### Multiple Environments

```jsonc
{
  "name": "my-app",
  "vars": {
    "ENVIRONMENT": "production",
    "API_URL": "https://api.example.com"
  },

  "env": {
    "staging": {
      "name": "my-app-staging",
      "vars": {
        "ENVIRONMENT": "staging",
        "API_URL": "https://staging-api.example.com"
      }
    },

    "production": {
      "name": "my-app-production",
      "vars": {
        "ENVIRONMENT": "production",
        "API_URL": "https://api.example.com"
      }
    }
  }
}
```

### Deploying to Environment

```bash
# Deploy to staging
npx wrangler deploy --env staging

# Deploy to production
npx wrangler deploy --env production
```

---

## Bindings Configuration

### KV Namespace

```jsonc
{
  "kv_namespaces": [
    {
      "binding": "MY_KV",
      "id": "your-kv-namespace-id",
      "preview_id": "your-preview-kv-id"
    }
  ]
}
```

**Usage in Astro:**
```javascript
const kv = Astro.locals.runtime.env.MY_KV;
const value = await kv.get("key");
await kv.put("key", "value", { expirationTtl: 3600 });
```

**Creating KV:**
```bash
npx wrangler kv:namespace create MY_KV
```

### D1 Database

```jsonc
{
  "d1_databases": [
    {
      "binding": "DB",
      "database_name": "my-database",
      "database_id": "your-d1-database-id"
    }
  ]
}
```

**Usage in Astro:**
```javascript
const db = Astro.locals.runtime.env.DB;
const result = await db.prepare("SELECT * FROM users").all();
```

**Creating D1:**
```bash
npx wrangler d1 create my-database
npx wrangler d1 execute my-database --file=./schema.sql
```

### R2 Storage

```jsonc
{
  "r2_buckets": [
    {
      "binding": "BUCKET",
      "bucket_name": "my-bucket"
    }
  ]
}
```

**Usage in Astro:**
```javascript
const bucket = Astro.locals.runtime.env.BUCKET;
await bucket.put("file.txt", "Hello World");
const object = await bucket.get("file.txt");
```

**Creating R2:**
```bash
npx wrangler r2 bucket create my-bucket
```

### Durable Objects

```jsonc
{
  "durable_objects": {
    "bindings": [
      {
        "name": "MY_DURABLE_OBJECT",
        "class_name": "MyDurableObject",
        "script_name": "durable-object-worker"
      }
    ]
  }
}
```

---

## Advanced Options

### Custom Routing

Create `_routes.json` in project root for advanced routing control:

```json
{
  "version": 1,
  "include": ["/*"],
  "exclude": ["/api/*", "/admin/*"]
}
```

- **include**: Patterns to route to Worker
- **exclude**: Patterns to serve as static assets

### Scheduled Tasks (Cron Triggers)

```jsonc
{
  "triggers": {
    "crons": [
      { "cron": "0 * * * *", "path": "/api/hourly" },
      { "cron": "0 0 * * *", "path": "/api/daily" }
    ]
  }
}
```

Create corresponding API routes:

```javascript
// src/pages/api/hourly.js
export async function GET({ locals }) {
  // Runs every hour
  return new Response("Hourly task complete");
}
```

### Rate Limiting

```jsonc
{
  "routes": [
    {
      "pattern": "api.example.com/*",
      "zone_name": "example.com"
    }
  ],
  "limits": {
    "cpu_ms": 50
  }
}
```

### Logging and Monitoring

```jsonc
{
  "logpush": true,
  "placement": {
    "mode": "smart"
  }
}
```

**View logs in real-time:**
```bash
npx wrangler tail
```

---

## TypeScript Configuration

### Complete tsconfig.json

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "allowJs": true,
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "types": ["@cloudflare/workers-types"],
    "jsx": "react-jsx",
    "jsxImportSource": "react"
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist"]
}
```

### Environment Type Definition

```typescript
// src/env.d.ts
/// <reference path="../.astro/types.d.ts" />

interface Env {
  // Cloudflare bindings
  MY_KV: KVNamespace;
  DB: D1Database;
  BUCKET: R2Bucket;

  // Environment variables
  API_URL: string;
  ENVIRONMENT: string;
  SECRET_VALUE?: string;
}

type Runtime = import('@astrojs/cloudflare').Runtime<Env>;

declare namespace App {
  interface Locals extends Runtime {}
}

declare namespace Astro {
  interface Locals extends Runtime {}
}
```

---

## Build Configuration

### package.json Scripts

```json
{
  "scripts": {
    "dev": "astro dev",
    "build": "astro build",
    "preview": "wrangler dev",
    "deploy": "npm run build && wrangler deploy",
    "deploy:staging": "npm run build && wrangler deploy --env staging",
    "cf:dev": "wrangler dev",
    "cf:dev:remote": "wrangler dev --remote",
    "cf:tail": "wrangler tail"
  }
}
```

### Vite Configuration

```javascript
// vite.config.js (if needed)
import { defineConfig } from 'vite';

export default defineConfig({
  build: {
    // Adjust chunk size warnings
    chunkSizeWarningLimit: 1000,
  },
});
```
