Cloudflare Integration
MIDDAG Account uses Cloudflare D1 and R2 as infrastructure services. D1 provides a read-replica edge database for the customer portal. R2 provides object storage for plugin ZIPs, documents, and other files. Workers, D1, and R2 are external infrastructure managed outside the plugin -- the plugin handles the WordPress side of synchronization.
Setup
API token
The plugin communicates with Cloudflare using an API token with permissions for D1 and R2. Configure it as an environment variable:
| Variable | Description |
|---|---|
CLOUDFLARE_API_TOKEN | Cloudflare API token |
CLOUDFLARE_ACCOUNT_ID | Cloudflare account ID |
The token should have the minimum required permissions: D1 read/write and R2 object read/write.
D1 -- Edge database
D1 acts as a read-replica cache for data that the customer portal (NextJS) accesses frequently. The WordPress plugin is the source of truth; D1 is a performance layer.
What gets cached
| Data | Source in plugin | Update method |
|---|---|---|
| Organization profiles | OrganizationService | Webhook (near-RT) |
| License statuses | LicenseService | Webhook (near-RT) |
| Product catalog | WooCommerce | Cron (periodic) |
| Plugin metadata | DownloadService | Cron (periodic) |
Synchronization
Two mechanisms keep D1 in sync:
Webhooks (near real-time): When relevant data changes (organization updated, license activated, order created), the plugin fires a webhook to a Cloudflare Workers endpoint via
do_action('middag_cloudflare_sync', $entity, $event).Cron (reconciliation): A periodic WP-Cron job syncs data in batches to catch any changes that webhooks may have missed.
Eventual consistency is acceptable for the portal. Critical operations (license validation, payment processing) always query the plugin's REST API directly.
Cache invalidation
When a product or document is updated, the plugin triggers invalidation in D1 and purges the Workers cache via the Cloudflare API.
R2 -- Object storage
R2 provides S3-compatible object storage. The plugin uses it for file distribution and document management.
Buckets
| Bucket | Contents | Managed by |
|---|---|---|
middag-plugins | Versioned WordPress plugin ZIP files | CI/CD + Plugin |
middag-documents | Contracts, invoice PDFs, terms | Plugin |
middag-app-cache | NextJS ISR cache | Workers |
Signed URLs
The plugin generates temporary pre-signed URLs for authorized downloads from R2. Before generating a URL, the plugin validates the requester's license or entitlement status. URLs expire after a configurable period.
Uploads
The plugin uploads documents (contracts, invoice PDFs) to R2 using the S3-compatible API. This happens automatically when a document is generated or attached to an entitlement.
Architecture
The plugin handles outbound data only. It pushes data to D1 and R2, and invalidates caches. It does not receive inbound data from Cloudflare.