Skip to main content

R2 on Cloudflare

R2 is Cloudflare's file storage. On Cloudflare Workers it is where the site keeps its files unless you choose otherwise, and it needs no keys: you create two buckets and bind them to the Worker. This page is for whoever deploys the site to Cloudflare. How files are stored explains the two stores first.

Create the two buckets​

Each store is a bucket of its own. The names are your choice; these match wrangler.toml.example:

npx wrangler r2 bucket create choir-public
npx wrangler r2 bucket create choir-private

Bind them to the Worker​

In wrangler.toml, the binding names must be exactly PUBLIC_BUCKET and PRIVATE_BUCKET. Only bucket_name is yours to choose:

# Public files: gallery, posters, uploaded images
[[r2_buckets]]
binding = "PUBLIC_BUCKET"
bucket_name = "choir-public"

# Member files and rehearsal tracks. Never give this bucket a public address:
# the Worker serves its objects itself, after checking who is asking.
[[r2_buckets]]
binding = "PRIVATE_BUCKET"
bucket_name = "choir-private"

Deploy again after changing the file. wrangler.toml explained covers the rest of the file.

You do not need to set STORAGE_PROVIDER: on Cloudflare it is r2 unless you say s3.

Keep the private bucket private​

Do not give the private bucket a public address, a custom domain or a public-access setting. Nothing links into it. A member's browser asks the Worker for a file, the Worker checks the login and then reads the file from the bucket itself.

The public bucket needs no public setting either. By default the Worker serves public files at /files/<key>. To serve them straight from R2 instead, give the public bucket a custom domain in Cloudflare and set PUBLIC_FILES_URL to it: see Public file addresses and upload limits and Cloudflare: your domain and public files.

Use S3 settings instead​

On Workers, STORAGE_PROVIDER=s3 switches to any S3-compatible service, R2 included, and then the bucket bindings are not read. You would do this to keep files outside Cloudflare. The settings are on S3-compatible storage.

If something goes wrong​

What you seeCause and fix
The Worker answers with an error, and the log (npx wrangler tail) says PUBLIC_BUCKET and PRIVATE_BUCKET R2 bindings are required (or set STORAGE_PROVIDER=s3)One or both bindings are missing from wrangler.toml, or are spelled differently. Add them as above and deploy again.
Upload failed in the admin panelThe reason is in the Worker log. Check that both buckets exist, in the same Cloudflare account as the Worker.
Files you uploaded are missing after you changed bucket_nameThe files are in the old bucket. A bucket's name is its identity; the site does not copy files between buckets.

Nothing in the site backs up or copies R2 buckets: see Back up PostgreSQL, MySQL, S3 storage and Cloudflare.