Skip to content

Cloudflare R2 buckets: public vs private access patterns

R2 has four distinct ways objects reach a caller: the r2.dev preview hostname, a custom-domain public bucket, an S3-style API token, and a Worker binding. Each one has different auth, caching, and pricing implications — pick wrong and you'll either burn through CPU time or expose objects you didn't mean to.

R2 is Cloudflare’s object store — S3-compatible API surface, no egress fees, billed on stored bytes plus class-A/class-B operations. The part that trips teams up isn’t the storage model; it’s the fact that R2 exposes four distinct access paths with four different auth and cache behaviors. A media bucket fronted by a custom domain serves cached objects from the edge for fractions of a cent. The same bucket served through a Worker that forgets to set Cache-Control re-reads R2 on every request and burns CPU time. This article walks the four patterns, when each one fits, and the bucket-level features (lifecycle rules, multipart uploads, object metadata) you should configure once and forget.

How to verify

Pick a bucket and inspect what’s actually configured. The S3-compatible endpoint lives at https://<account-id>.r2.cloudflarestorage.com. You need an R2 API token (generated in the dashboard under R2 > Manage R2 API Tokens) to talk to it.

# List your buckets via the S3 API
aws s3 ls \
  --endpoint-url https://<account-id>.r2.cloudflarestorage.com \
  --profile r2

# Check whether public access is enabled for a bucket
curl -sS -X GET "https://api.cloudflare.com/client/v4/accounts/<account-id>/r2/buckets/<bucket>" \
  -H "Authorization: Bearer <CF_API_TOKEN>" | jq

# List custom domains attached to the bucket
curl -sS -X GET "https://api.cloudflare.com/client/v4/accounts/<account-id>/r2/buckets/<bucket>/domains/custom" \
  -H "Authorization: Bearer <CF_API_TOKEN>" | jq

# Inspect object metadata (HEAD via S3 API)
aws s3api head-object \
  --bucket <bucket> \
  --key path/to/object.jpg \
  --endpoint-url https://<account-id>.r2.cloudflarestorage.com

The head-object response shows ContentType, ContentLength, ETag, LastModified, and any custom metadata you set via the x-amz-meta-* headers at upload time. The dashboard (R2 > your bucket > Settings) shows the four toggles that matter for this article: r2.dev access, Custom Domains, CORS Policy, and Object Lifecycle Rules.

What’s happening

R2 separates storage from access deliberately. The bucket itself is a private container — by default nothing outside your account reaches it. Each access pattern is a separate opt-in that determines who can read or write, whether the response is cached at the edge, and how requests are billed.

Four ways a caller reaches the same R2 bucketBrowser /app callerpublic, no cache<pub-id>.r2.dev hostnamepublic, cachedcustom domain (CDN)private, signedS3 API + API tokenvia your codeWorker binding (env.MY_R2)R2 bucketobjects + metadatalifecycle rulesStorage is one container. Each access path is an independent opt-in with different auth, cache, and billing behavior.
The four ways a caller reaches a single R2 bucket. Each row is a separate configuration; bucket storage is shared.

The four patterns:

Public via r2.dev. Cloudflare assigns each bucket an opt-in development hostname of the form pub-<32-hex-chars>.r2.dev. Enable it in the dashboard and any object becomes readable by anyone with the URL. Useful for one-off testing and internal demos. The catch: r2.dev is explicitly rate-limited and is not cached at the edge. Treat it as a debug hostname, not a production CDN. Cloudflare’s documentation is clear that production traffic should use a custom domain instead.

Public via custom domain. Attach a hostname like cdn.example.com to the bucket. Cloudflare proxies the bucket behind its CDN — the first request fetches from R2 storage, subsequent requests at the same colo serve from cache. This is the production pattern for any static asset: images, fonts, video segments, downloadable installers. You get the full Cache Rules layer (Cache-Control on the object, plus dashboard rules), HTTPS via universal certs, and zero egress charges. The trade-off: the bucket is genuinely public; anyone who guesses or scrapes a URL can read.

Private via S3 API. The S3-compatible endpoint at <account-id>.r2.cloudflarestorage.com requires Signature V4 authentication with an R2 API token. This is how server-side code, backup jobs, and migration tools talk to R2. The endpoint is not cached and the request path is direct to the R2 origin — fine for low-volume back-office traffic, expensive (in operation count, not in time) if you use it as a CDN.

Private via Worker. Bind the bucket into a Worker as an environment variable, then write code that fetches from env.MY_BUCKET.get(key) and returns a Response. You control auth (cookie check, JWT, HMAC), cache headers, transformations (image resizing, range slicing), and access logging. The Worker runs at the edge and is cached if you set the right headers. This is the right pattern for user-uploaded files, paid downloads, anything that needs even basic authorization.

The bucket itself stores objects up to 5 TB (with the multipart upload API for anything above ~5 GB). Each object carries a key, a content type, an ETag (MD5 of the content for single-part uploads, a different scheme for multipart), and arbitrary user metadata set via x-amz-meta-* headers. Metadata is returned on every GET and HEAD — use it for content fingerprints, upload provenance, or anything you’d otherwise stuff into a side table.

The procedure

1. Create the bucket. Two ways — both work, pick whichever fits your provisioning model.

# Via wrangler
npx wrangler r2 bucket create media-prod

# Via API
curl -sS -X POST "https://api.cloudflare.com/client/v4/accounts/<account-id>/r2/buckets" \
  -H "Authorization: Bearer <CF_API_TOKEN>" \
  -H "Content-Type: application/json" \
  --data '{"name":"media-prod","locationHint":"weur"}'

The locationHint is a soft preference (apac, eeur, enam, weur, wnam); R2 stores authoritative replicas in the chosen region and serves through Cloudflare’s network from elsewhere.

2. Decide the access pattern, then enable it. Match the use case to the four paths.

Use caseAccess pattern
Public website images, fonts, downloadable installersCustom domain
User avatars (public, but with cache invalidation on upload)Custom domain + cache purge in upload Worker
User-uploaded private documents, paid downloadsWorker binding + auth check
Server-side backup target, migration source/targetS3 API token (scoped to the one bucket)
Internal demo while you wire up the real frontendr2.dev (then turn it off before production)

To attach a custom domain, point a hostname at the bucket in the dashboard (R2 > bucket > Settings > Custom Domains) or via API:

curl -sS -X POST "https://api.cloudflare.com/client/v4/accounts/<account-id>/r2/buckets/media-prod/domains/custom" \
  -H "Authorization: Bearer <CF_API_TOKEN>" \
  -H "Content-Type: application/json" \
  --data '{"domain":"cdn.example.com","enabled":true}'

Cloudflare provisions a TLS cert and points the proxy at the bucket automatically. For the Worker binding pattern, see the companion article serving R2 objects through Workers with signed URLs.

3. Set Cache-Control at upload time. This is the single most important configuration choice and the one most teams get wrong. When you PUT an object, set Cache-Control: public, max-age=31536000, immutable for content-hashed filenames (app.7f3a9.js), or max-age=86400 for content that changes under a stable URL. Without a Cache-Control header, Cloudflare’s CDN uses its default — typically not what you want.

aws s3 cp ./build/app.7f3a9.js s3://media-prod/app.7f3a9.js \
  --endpoint-url https://<account-id>.r2.cloudflarestorage.com \
  --cache-control "public, max-age=31536000, immutable" \
  --content-type "application/javascript"

4. Configure multipart uploads for large objects. Single-part uploads cap at 5 GB. For anything larger — and ideally anything over ~100 MB — use multipart. Most S3 SDKs do this automatically once you cross a threshold (aws-cli defaults to multipart for files over 8 MB). rclone and wrangler r2 object put handle it too. Each part is at least 5 MB except the last; the upload is committed atomically via CompleteMultipartUpload. Failed multipart uploads leave incomplete parts behind that you still pay for until you abort them or a lifecycle rule cleans them up.

5. Add a lifecycle rule for incomplete multipart uploads. Set it on every bucket — there is no good reason not to.

curl -sS -X PUT "https://api.cloudflare.com/client/v4/accounts/<account-id>/r2/buckets/media-prod/lifecycle" \
  -H "Authorization: Bearer <CF_API_TOKEN>" \
  -H "Content-Type: application/json" \
  --data '{
    "rules": [
      {
        "id": "abort-stale-multipart",
        "enabled": true,
        "conditions": {"prefix": ""},
        "abortMultipartUploadsTransition": {"condition": {"maxAge": 604800}}
      }
    ]
  }'

That rule aborts any multipart upload still pending after seven days. Add a deletion rule for transient prefixes (tmp/, uploads/staging/) if your app uses them.

6. CORS, if browsers will hit the bucket directly. Set the CORS policy on the bucket (dashboard or API). Without it, a fetch from app.example.com to cdn.example.com for a font file will fail in Chrome. The policy is bucket-scoped and supports the standard origin list, methods, and exposed headers.

Picking the access patternWho reads the objects?anyoneauthorized callers onlyProduction traffic?noyesr2.dev hostnamecustom domainServer or browser?serverbrowserS3 API tokenWorker binding
Decision tree for picking the right R2 access pattern.

Common pitfalls

  • Leaving the r2.dev hostname enabled in production — it’s rate-limited, uncached, and exposes the pub-<id>.r2.dev URL forever; turn it off once the custom domain is live.
  • Forgetting Cache-Control headers on upload, then wondering why a 200 MB video bills cache MISSes on every request.
  • Issuing R2 API tokens with account-wide read/write when a single-bucket token would do — scope tokens to one bucket and one permission set.
  • Treating S3 API access from the public internet as a CDN; it’s not cached and you’re paying class-B operations on every GET.
  • Not setting an abort-multipart lifecycle rule, then discovering a backup tool has left tens of GB of orphaned upload parts.

In the engagements we run, R2 typically replaces a multi-region S3 setup that was bleeding egress to a CDN. The first thing we audit when taking over a Cloudflare estate is which buckets are exposed via r2.dev, which have no Cache-Control discipline, and which are using account-scoped API tokens when a bucket-scoped token would do. Managed Operations is the layer where we own that posture so your team can keep shipping.