Documentation
¶
Overview ¶
Package cloudflare implements the Cloudflare Workers and R2 serverless provider.
Index ¶
- func CloudflareAssetBucketName(appName, environment string) string
- func CloudflareWorkerName(appName, environment string) string
- type CFTailEventDetail
- type CFTailException
- type CFTailLogEntry
- type CFTailMessage
- type CFTailRequest
- type CFTailResponse
- type CloudflareProvider
- func (p *CloudflareProvider) Apply(ctx context.Context, cfg *config.NextDeployConfig) (*PlanResult, error)
- func (p *CloudflareProvider) DeployCompute(ctx context.Context, pkg *packaging.PackageResult, ...) error
- func (p *CloudflareProvider) DeployStatic(ctx context.Context, pkg *packaging.PackageResult, ...) error
- func (p *CloudflareProvider) Destroy(ctx context.Context, cfg *config.NextDeployConfig) error
- func (p *CloudflareProvider) GetResourceMap(ctx context.Context, cfg *config.NextDeployConfig) (core.ServerlessResourceMap, error)
- func (p *CloudflareProvider) GetSecrets(ctx context.Context, appName string) (map[string]string, error)
- func (p *CloudflareProvider) Initialize(ctx context.Context, cfg *config.NextDeployConfig) error
- func (p *CloudflareProvider) InvalidateCache(ctx context.Context, cfg *config.NextDeployConfig) error
- func (p *CloudflareProvider) Plan(ctx context.Context, cfg *config.NextDeployConfig) (*PlanResult, error)
- func (p *CloudflareProvider) ProvisionResources(ctx context.Context, cfg *config.NextDeployConfig) (retErr error)
- func (p *CloudflareProvider) QueryLogs(ctx context.Context, cfg *config.NextDeployConfig, opts QueryOptions) (*logs.AnalysisReport, error)
- func (p *CloudflareProvider) Rollback(ctx context.Context, cfg *config.NextDeployConfig, opts core.RollbackOptions) error
- func (p *CloudflareProvider) SetSecret(ctx context.Context, appName, key, value string) error
- func (p *CloudflareProvider) SyncResourceState(ctx context.Context, cfg *config.NextDeployConfig) error
- func (p *CloudflareProvider) TailLogs(ctx context.Context, cfg *config.NextDeployConfig, routeFilter string, ...) error
- func (p *CloudflareProvider) TailLogsWithOptions(ctx context.Context, cfg *config.NextDeployConfig, opts TailOptions, ...) error
- func (p *CloudflareProvider) UnsetSecret(ctx context.Context, appName, key string) error
- func (p *CloudflareProvider) UpdateSecrets(ctx context.Context, appName string, secrets map[string]string) error
- type PlanAction
- type PlanItem
- type PlanResult
- type QueryOptions
- type TailOptions
- type UnmanagedResource
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CloudflareAssetBucketName ¶
CloudflareAssetBucketName is the env-scoped R2 asset bucket for an app. Same namespacing rule as CloudflareWorkerName.
func CloudflareWorkerName ¶
CloudflareWorkerName returns the Worker script name for an app+environment. Exported so the CLI can print it (preview-URL composition) and tests can assert it without constructing a provider.
The environment IS the namespace: "" (→ production) yields <app>-production, "pr-42" yields <app>-pr-42 — a completely separate Worker script. That's what makes per-PR preview stacks, and their teardown, safe by construction.
Types ¶
type CFTailEventDetail ¶
type CFTailEventDetail struct {
Request *CFTailRequest `json:"request"`
Response *CFTailResponse `json:"response"`
}
type CFTailException ¶
type CFTailLogEntry ¶
type CFTailMessage ¶
type CFTailMessage struct {
Outcome string `json:"outcome"`
ScriptName string `json:"scriptName"`
EventTimestampMs int64 `json:"eventTimestampMs"`
EventType string `json:"eventType"`
Logs []CFTailLogEntry `json:"logs"`
Exceptions []CFTailException `json:"exceptions"`
Event *CFTailEventDetail `json:"event"`
CPUTimeMs float64 `json:"cpuTimeMs"`
WallTimeMs float64 `json:"wallTimeMs"`
}
CFTailMessage represents the JSON payload pushed by Cloudflare's Tail WebSocket.
type CFTailRequest ¶
type CFTailResponse ¶
type CFTailResponse struct {
Status int `json:"status"`
}
type CloudflareProvider ¶
type CloudflareProvider struct {
// contains filtered or unexported fields
}
CloudflareProvider implements Provider for Cloudflare Workers + R2.
IMPORTANT — Next.js compatibility status:
Cloudflare Workers do not run vanilla Node.js, so a Next.js standalone build cannot be uploaded as-is. Production deployments require the build to be adapted into a Worker-compatible bundle (see the cloudflare adapter step in the packager). Until that lands, DeployCompute will log a loud warning when given a non-static-export build.
SDK usage:
- Management plane (workers, secrets, routes, R2 buckets, zone, cache): github.com/cloudflare/cloudflare-go/v6
- R2 object plane (PUT/GET/DELETE objects): the SDK does not cover this; we use the AWS S3 SDK pointed at R2's S3-compatible endpoint (https://<account>.r2.cloudflarestorage.com).
Credentials (resolved in this order — first non-empty wins):
- Environment variables (CI-friendly, ephemeral)
- Encrypted credstore at ~/.nextdeploy/credstore (per-machine, mode 0600)
- Plaintext nextdeploy.yml (LEGACY — emits a loud WARN; prefer 1 or 2)
Field map:
- CF API token: CLOUDFLARE_API_TOKEN | credstore[cloudflare].api_token | cloudprovider.access_key
- CF account ID: CLOUDFLARE_ACCOUNT_ID | credstore[cloudflare].account_id | cloudprovider.account_id
- R2 access key: R2_ACCESS_KEY_ID | credstore[cloudflare].r2_access_key_id | (no yaml fallback)
- R2 secret key: R2_SECRET_ACCESS_KEY | credstore[cloudflare].r2_secret_key | (no yaml fallback)
Every resolved value is registered with the sensitive scrubber so it never leaks into log lines or error messages.
func NewCloudflareProvider ¶
func NewCloudflareProvider() *CloudflareProvider
func (*CloudflareProvider) Apply ¶
func (p *CloudflareProvider) Apply(ctx context.Context, cfg *config.NextDeployConfig) (*PlanResult, error)
Apply reconciles the declared IaC layer: it computes a read-only plan (the diff), then provisions everything that is missing (create-if-absent), returning the plan so the caller can report what was created / updated / already in place.
This is the "recreate resources" path: a D1 database, KV namespace, queue, Hyperdrive config, etc. that was deleted out-of-band shows up as a Create in the plan and is recreated by ProvisionResources. Re-running is safe — already existing resources are no-ops, and D1 migrations are idempotent (tracked in the _nextdeploy_migrations table), so a recreated database re-applies its schema exactly once.
Apply stops on the first immutable drift (e.g. Vectorize dimension change), surfacing it instead of silently destroying data.
func (*CloudflareProvider) DeployCompute ¶
func (p *CloudflareProvider) DeployCompute(ctx context.Context, pkg *packaging.PackageResult, cfg *config.NextDeployConfig, meta *nextcore.NextCorePayload) error
DeployCompute adapts the Next.js standalone build into a Worker bundle (using esbuild + the embedded shim) and uploads it via the SDK.
For static-export sites, no compute deploy is needed — DeployStatic + a catch-all R2 worker is sufficient. We skip in that case.
func (*CloudflareProvider) DeployStatic ¶
func (p *CloudflareProvider) DeployStatic(ctx context.Context, pkg *packaging.PackageResult, cfg *config.NextDeployConfig, meta *nextcore.NextCorePayload) error
DeployStatic uploads the package's static assets to an R2 bucket via the S3-compatible endpoint. R2 management (bucket creation) goes through the official SDK.
R2 object PUTs use S3-protocol HMAC auth, not Bearer; cloudflare-go doesn't expose object operations. Credential resolution order, designed so the zero-config path is the default:
- Explicit long-lived pair (R2_ACCESS_KEY_ID + R2_SECRET_ACCESS_KEY in env / credstore). Used as-is. Preserves existing CI configs.
- **Auto-derived from the CF API token.** Per CF's R2 docs, the access key id is the API token's `id` (captured in verifyToken via /user/tokens/verify) and the secret access key is SHA-256 of the token's `value`. No dashboard click, no extra scope beyond "Workers R2 Storage: Edit", no minting endpoint. This is the intended one-token-end-to-end path.
- Parent-key fallback (R2_PARENT_ACCESS_KEY_ID set): mint a 1-hour scoped child via /accounts/:id/r2/temp-access-credentials. Useful when the API token deliberately doesn't have R2 scope but a dedicated R2 parent key does.
- None of the above — fail with dashboard URL.
func (*CloudflareProvider) Destroy ¶
func (p *CloudflareProvider) Destroy(ctx context.Context, cfg *config.NextDeployConfig) error
Destroy tears down everything nextdeploy created for this app: the Worker (its routes + secrets go with it), the R2 bucket (objects swept first, since CF refuses to delete a non-empty bucket), every provisioned resource recorded in the cfstate manifest (D1/KV/Hyperdrive/Queues/Vectorize/AI Gateway), and the DNS records it added. Anything that can't be deleted is reported and makes Destroy return an error, so the operator is never told "done" while resources (and billing) survive. 404s are treated as already-gone.
func (*CloudflareProvider) GetResourceMap ¶
func (p *CloudflareProvider) GetResourceMap(ctx context.Context, cfg *config.NextDeployConfig) (core.ServerlessResourceMap, error)
func (*CloudflareProvider) GetSecrets ¶
func (p *CloudflareProvider) GetSecrets(ctx context.Context, appName string) (map[string]string, error)
GetSecrets lists secret names. The CF API never returns secret values.
func (*CloudflareProvider) Initialize ¶
func (p *CloudflareProvider) Initialize(ctx context.Context, cfg *config.NextDeployConfig) error
Initialize wires up the Cloudflare SDK client and verifies the API token.
The deploy is designed around a single-token UX: the user sets CLOUDFLARE_API_TOKEN and everything else (account ID, optionally R2 credentials) is derived. If they want explicit overrides, env or credstore wins.
func (*CloudflareProvider) InvalidateCache ¶
func (p *CloudflareProvider) InvalidateCache(ctx context.Context, cfg *config.NextDeployConfig) error
InvalidateCache purges the Cloudflare zone cache for the configured domain.
func (*CloudflareProvider) Plan ¶
func (p *CloudflareProvider) Plan(ctx context.Context, cfg *config.NextDeployConfig) (*PlanResult, error)
Plan computes a dry-run diff for every IaC resource declared under cfg.Serverless.Cloudflare.Resources. Read-only: makes GET / List calls against the CF API but no mutations. Caller must have already called Initialize() so p.cf is wired.
Scope: hyperdrive, queues, vectorize, ai_gateway, dns. Custom domains and routes are tied to worker upload (not standalone resources) and so are not planned here — they're computed during DeployCompute.
func (*CloudflareProvider) ProvisionResources ¶
func (p *CloudflareProvider) ProvisionResources(ctx context.Context, cfg *config.NextDeployConfig) (retErr error)
ProvisionResources walks cfg.Serverless.Cloudflare.Resources and calls the matching ensure* helper for each declared resource. Stops on first error. Results are stashed on p.provisioned for binding ref resolution at upload time. Safe to call before DeployCompute.
func (*CloudflareProvider) QueryLogs ¶ added in v1.2.0
func (p *CloudflareProvider) QueryLogs(ctx context.Context, cfg *config.NextDeployConfig, opts QueryOptions) (*logs.AnalysisReport, error)
QueryLogs fetches recent telemetry events for the Worker via Cloudflare's Workers Observability API, merges multi-fragment request logs, classifies fault ownership, and returns an AnalysisReport.
func (*CloudflareProvider) Rollback ¶
func (p *CloudflareProvider) Rollback(ctx context.Context, cfg *config.NextDeployConfig, opts core.RollbackOptions) error
Rollback reverts the Worker to a previous deployment version, either by git commit prefix (--to <commit>, matched against workers/message annotations stamped during deploy) or by step count (--steps N).
func (*CloudflareProvider) SetSecret ¶
func (p *CloudflareProvider) SetSecret(ctx context.Context, appName, key, value string) error
func (*CloudflareProvider) SyncResourceState ¶
func (p *CloudflareProvider) SyncResourceState(ctx context.Context, cfg *config.NextDeployConfig) error
SyncResourceState pulls the encrypted resource manifest from R2 and merges it with local state. Remote sync is enabled by setting NEXTDEPLOY_CF_STATE_KEY to the same secret on each developer machine and CI runner.
func (*CloudflareProvider) TailLogs ¶
func (p *CloudflareProvider) TailLogs(ctx context.Context, cfg *config.NextDeployConfig, routeFilter string, out io.Writer) error
TailLogs streams live logs from a Cloudflare Worker using Cloudflare's Tail WebSocket API natively. Automatically reconnects on connection drops or session expiration without requiring external tools like Wrangler.
func (*CloudflareProvider) TailLogsWithOptions ¶ added in v1.2.0
func (p *CloudflareProvider) TailLogsWithOptions(ctx context.Context, cfg *config.NextDeployConfig, opts TailOptions, out io.Writer) error
TailLogsWithOptions streams live logs from a Cloudflare Worker with fault-ownership classification and filtering.
func (*CloudflareProvider) UnsetSecret ¶
func (p *CloudflareProvider) UnsetSecret(ctx context.Context, appName, key string) error
func (*CloudflareProvider) UpdateSecrets ¶
func (p *CloudflareProvider) UpdateSecrets(ctx context.Context, appName string, secrets map[string]string) error
UpdateSecrets stashes a batch of secrets onto the provider so DeployCompute can fold them into the next Workers.Scripts.Update call as secret_text bindings. This bypasses CF's per-secret PUT endpoint (rate-limited at ~13 req/s, error 10013) and lands every secret atomically in a single upload.
Trade-off: secret rotation requires a Worker re-upload. That re-upload is cheap because the bundle is content-hashed and reused — only the metadata changes — but it does mean `nextdeploy secrets set FOO=bar` outside of a full deploy uses the per-secret path (SetSecret/UnsetSecret) instead of going through here.
Calling UpdateSecrets with an empty map clears the staged set.
type PlanAction ¶
type PlanAction string
PlanAction is the verdict the diff engine emits for each declared resource. "immutable-drift" is its own action (vs. error) so the renderer can surface every problem in one pass instead of bailing on the first immutable mismatch.
const ( PlanCreate PlanAction = "create" PlanUpdate PlanAction = "update" PlanNoOp PlanAction = "no-op" PlanImmutableDrift PlanAction = "immutable-drift" )
type PlanItem ¶
type PlanItem struct {
Kind string
Name string
Action PlanAction
Detail string
}
PlanItem is one row in the plan output. Detail is human-readable; for NoOp it is empty, for Update it describes the field-level diff, for Drift it explains the immutable mismatch.
type PlanResult ¶
type PlanResult struct {
Items []PlanItem
// Warnings are advisory lines that aren't tied to a single declared
// resource: declared-but-unwired features, and account resources that look
// like they belong to this app but are no longer declared. They never
// block an apply — they exist so the gap isn't silent.
Warnings []string
}
PlanResult is the full diff bundle. HasDrift() flags whether any item is ImmutableDrift so the cmd can exit non-zero (CI-friendly).
func (*PlanResult) HasChanges ¶
func (r *PlanResult) HasChanges() bool
HasChanges reports whether the plan includes creates, updates, or immutable drifts.
func (*PlanResult) HasDrift ¶
func (r *PlanResult) HasDrift() bool
type QueryOptions ¶ added in v1.2.0
type QueryOptions struct {
Since time.Duration
RouteFilter string
OwnerFilter logs.Owner
ErrorsOnly bool
MaxEvents int
NDJSONOut io.Writer
}
QueryOptions configures historical Cloudflare Workers Observability queries.
type TailOptions ¶ added in v1.2.0
type TailOptions struct {
RouteFilter string
ErrorsOnly bool
OwnerFilter logs.Owner
Raw bool
QuietAssets bool
NDJSONOut io.Writer
}
TailOptions configures filtering, fault-ownership formatting, and NDJSON export during live tailing.
type UnmanagedResource ¶
UnmanagedResource is an account resource that looks like it belongs to this app (it matches the app's name prefix) but is not declared in nextdeploy.yml.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package adapter compiles and bundles Next.js standalone builds for Cloudflare Workers.
|
Package adapter compiles and bundles Next.js standalone builds for Cloudflare Workers. |
|
Package cfstate is the persistent, encrypted record of the Cloudflare resources NextDeploy has provisioned (D1, KV, Hyperdrive, Queues, Vectorize, …) keyed by kind+name → real CF ID.
|
Package cfstate is the persistent, encrypted record of the Cloudflare resources NextDeploy has provisioned (D1, KV, Hyperdrive, Queues, Vectorize, …) keyed by kind+name → real CF ID. |