Files
shit_in_a_vault/000-configs/tools/CLOUDFLARE_INSTRUCTIONS.md

397 lines
7.3 KiB
Markdown

---
title: "Cloudflare Platform"
status: "active"
folder: "000-configs/tools"
tags: [tool, cloudflare, workers, r2, d1, kv, ai, hosting]
created: "2026-07-29"
updated: "2026-07-30"
version: "1.2.0"
---
# Cloudflare Platform Instructions
Cloudflare is the **hosting and edge platform** for this workspace. Use Workers (serverless functions), Pages (static sites), R2 (object storage), D1 (SQLite at the edge), KV (key-value), Workers AI, and the Agents SDK.
Credentials are in `/home/user/.env.cloudflare` (server-only file, chmod 600, NOT in repo). Load with `source /home/user/.env.cloudflare`.
Admin placeholder: `[[000-shit_admin/cloudflare]]` (gitignored, just points to the env file).
## Quick Reference
- **CLI:** `npx wrangler` (not installed globally — use npx)
- **Account ID:** see admin doc
- **API Token:** see admin doc
- **Auth check:** `npx wrangler whoami`
- **Docs:** https://developers.cloudflare.com/
---
## 1. First-Time Setup
```bash
# Verify CLI is reachable
npx wrangler --version
# Login (uses browser-based OAuth)
npx wrangler login
# Verify auth
npx wrangler whoami
```
If `wrangler login` is not possible in the environment, set the API token directly:
```bash
# Load from server-only .env file
source /home/user/.env.cloudflare
# or set manually:
export CLOUDFLARE_API_TOKEN="<token>"
export CLOUDFLARE_ACCOUNT_ID="<account id>"
```
**Verify token works:**
```bash
curl -X GET "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/tokens/verify" \
-H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}"
```
---
## 2. Workers (Serverless Functions)
### Create a new Worker
```bash
npx wrangler init my-worker
cd my-worker
```
### Deploy
```bash
npx wrangler deploy
```
### Local dev
```bash
npx wrangler dev
# runs at http://localhost:8787
```
### Tail logs
```bash
npx wrangler tail
# real-time logs from production
```
### Set secrets (env vars)
```bash
echo "secret-value" | npx wrangler secret put SECRET_NAME
```
---
## 3. R2 (Object Storage)
S3-compatible blob storage. Cheaper than AWS S3.
### Create bucket
```bash
npx wrangler r2 bucket create my-bucket
```
### List buckets
```bash
npx wrangler r2 bucket list
```
### Upload file
```bash
npx wrangler r2 object put my-bucket/path/to/file.txt --file ./local-file.txt
```
### Download file
```bash
npx wrangler r2 object get my-bucket/path/to/file.txt --file ./downloaded.txt
```
### Direct API (S3-compatible)
Endpoint format: `https://<ACCOUNT_ID>.r2.cloudflarestorage.com`
```bash
# Credentials are in admin doc
ACCESS_KEY_ID="<from admin doc>"
SECRET_ACCESS_KEY="<from admin doc>"
ENDPOINT="https://<ACCOUNT_ID>.r2.cloudflarestorage.com"
# Upload via AWS CLI (or any S3 client)
aws s3 cp ./file.txt s3://my-bucket/file.txt \
--endpoint-url "$ENDPOINT" \
--access-key-id "$ACCESS_KEY_ID" \
--secret-access-key "$SECRET_ACCESS_KEY"
```
---
## 4. D1 (SQLite at the Edge)
Distributed SQLite database.
### Create database
```bash
npx wrangler d1 create my-db
# outputs: database_id = "xxxx-xxxx-xxxx"
```
### Run migrations
```bash
npx wrangler d1 migrations create my-db create_users_table
npx wrangler d1 migrations apply my-db --remote
```
### Execute SQL
```bash
npx wrangler d1 execute my-db --command "SELECT * FROM users"
```
### Local dev DB
```bash
npx wrangler d1 execute my-db --local --command "SELECT * FROM users"
```
---
## 5. KV (Key-Value Store)
Low-latency global KV.
### Create namespace
```bash
npx wrangler kv namespace create MY_KV
# outputs: id = "xxxx"
```
### Write / read
```bash
npx wrangler kv key put --namespace-id=<id> "my-key" "my-value"
npx wrangler kv key get --namespace-id=<id> "my-key"
```
---
## 6. Workers AI
```bash
npx wrangler ai run "@cf/meta/llama-3.1-8b-instruct" \
--prompt "Hello world"
```
Models list: https://developers.cloudflare.com/workers-ai/models/
---
## 7. Pages (Static Sites)
### Deploy
```bash
npx wrangler pages deploy ./dist --project-name=my-site
```
### Local dev
```bash
npx wrangler pages dev ./dist
```
---
## 8. wrangler.jsonc Config
Prefer JSON config over TOML. Newer features are JSON-only.
```jsonc
{
"name": "my-worker",
"main": "src/index.ts",
"compatibility_date": "2026-07-15",
"compatibility_flags": ["nodejs_compat"],
"vars": {
"ENV": "production"
},
"kv_namespaces": [
{
"binding": "MY_KV",
"id": "xxxx"
}
],
"r2_buckets": [
{
"binding": "MY_BUCKET",
"bucket_name": "my-bucket"
}
],
"d1_databases": [
{
"binding": "DB",
"database_name": "my-db",
"database_id": "xxxx"
}
],
"ai": {
"binding": "AI"
}
}
```
After config changes, regenerate TypeScript bindings:
```bash
npx wrangler types
```
---
## 9. Local Dev Defaults
- Bindings use **local simulation** unless `remote: true`
- KV, R2, D1 all have local SQLite-backed emulators
- For real cloud data in dev:
```bash
npx wrangler dev --remote
```
---
## 10. Profiles
Use environments for staging/prod:
```jsonc
{
"env": {
"staging": {
"name": "my-worker-staging",
"vars": { "ENV": "staging" }
},
"production": {
"name": "my-worker-prod",
"vars": { "ENV": "production" }
}
}
}
```
Deploy to env:
```bash
npx wrangler deploy --env staging
npx wrangler deploy --env production
```
---
## 11. Common Patterns
### Cron-triggered Worker
```jsonc
{
"triggers": {
"crons": ["*/5 * * * *"] // every 5 min
}
}
```
### Queue consumer
```jsonc
{
"queues": {
"consumers": [{ "queue": "my-queue", "max_batch_size": 10 }]
}
}
```
### Durable Object
```jsonc
{
"durable_objects": {
"bindings": [
{ "name": "COUNTER", "class_name": "Counter" }
]
},
"migrations": [
{ "tag": "v1", "new_sqlite_classes": ["Counter"] }
]
}
```
---
## 12. Skills (Loaded on Demand)
The following skills live in `/home/user/.agents/skills/`:
| Skill | When to load |
|---|---|
| `cloudflare` | General Cloudflare platform questions |
| `wrangler` | CLI commands, flags, config reference |
| `workers-best-practices` | Worker architecture, performance |
| `durable-objects` | DO patterns, migrations |
| `cloudflare-email-service` | Email routing/workers |
| `cloudflare-one` | Zero Trust, Tunnel, Access |
| `cloudflare-one-migrations` | Migrate from other providers |
| `sandbox-sdk` | Sandboxed code execution |
| `turnstile-spin` | CAPTCHA integration |
| `web-perf` | Performance tuning |
Load via `view_skill` tool or read `SKILL.md` directly.
---
## 13. Failure Modes to Avoid
- ❌ Don't hardcode credentials in source — use `wrangler secret`
- ❌ Don't commit `wrangler.jsonc` with secrets — only bindings/IDs
- ❌ Don't use TOML — prefer `wrangler.jsonc`
- ❌ Don't skip `compatibility_date` — always set a recent one
- ❌ Don't edit local DB and assume it's in prod — use `--remote` flag
- ❌ Don't run `wrangler deploy` without testing locally first
- ❌ Don't paste API tokens in chat — read from admin doc at runtime
---
## 14. Auth Priority
When loading the workspace prompt, prefer:
1. `wrangler login` (OAuth, persists)
2. `CLOUDFLARE_API_TOKEN` env var (read from admin doc)
3. Hardcoded token (worst, only for one-off scripts)
---
## Related Docs
- [[GH_CLI_INSTRUCTIONS]] — GitHub
- [[VITE_PREVIEW_INSTRUCTIONS]] — Vite preview
- [[PLAYWRIGHT_BROWSER_INSTRUCTIONS]] — Browser automation
- [[000-shit_admin/cloudflare]] — admin creds (read-only)