Cloudflare R2 is the object store we reach for when a file has to be uploaded once, kept for a defined time and served to the public. This post covers what ran on it in production: customer-uploaded print files for personalized storefronts, publicly served images, and an S3-compatible driver design that keeps the provider a configuration choice. It extends the move of 15 WordPress sites to Cloudflare Workers, where the static pages live on Workers and the mutable files do not.
What is R2 object storage?
R2 is object storage that exposes the S3 API and charges nothing for egress to the internet. You create a bucket, put objects under keys, and read them back over HTTPS or through the S3 endpoint. The endpoint takes the form https://<ACCOUNT_ID>.r2.cloudflarestorage.com, and the region is auto (R2 S3 API).
R2 is S3-compatible, not S3-identical. Cloudflare’s compatibility page lists unimplemented operations, including object tagging, versioning, replication, bucket policy and object lock, and storage classes are limited to Standard and Infrequent Access (R2 S3 API). If your application uses none of those, existing S3 clients work with a new endpoint. If it does, you find out at integration time, not after migration.
How much does Cloudflare R2 cost?
Standard storage is $0.015 per GB-month. Class A operations (writes and listings) cost $4.50 per million, Class B operations (reads) cost $0.36 per million, and egress is free. The monthly free tier on Standard storage is 10 GB-month, 1 million Class A operations and 10 million Class B operations (R2 pricing).
| Standard | Infrequent Access | |
|---|---|---|
| Storage | $0.015 per GB-month | $0.01 per GB-month |
| Class A operations | $4.50 per million | $9.00 per million |
| Class B operations | $0.36 per million | $0.90 per million |
| Data retrieval | None | $0.01 per GB |
| Minimum storage duration | None stated | 30 days |
| Egress to the internet | Free | Free |
The shape of that table decides what belongs where. Public images are read-heavy and small, so free egress and cheap Class B reads dominate and Standard fits. Backups that are rarely restored fit Infrequent Access, but the retrieval fee and 30-day minimum mean it is the wrong class for anything that is overwritten daily.
The free tier is not a reason to design around it. On a production workload, count operations as well as gigabytes: a listing-heavy job that walks a large bucket every hour spends Class A operations, which cost twelve and a half times a Class B read.
R2 vs S3: how do they differ?
They differ on egress, on feature coverage and on where the control plane sits. R2 charges no egress fee; S3 charges for data transferred out to the internet, so the same traffic costs different amounts depending on the provider. This post does not quote S3 prices, since the comparison belongs on AWS’s own pricing page and it changes.
| Cloudflare R2 | Amazon S3 | |
|---|---|---|
| API | S3-compatible subset | The reference S3 API |
| Egress to the internet | Free | Charged |
| Versioning, replication, object lock | Not implemented per the compatibility page | Supported |
| Object tagging | Not implemented | Supported |
| Public serving with caching | Custom domain through Cloudflare | Needs a CDN in front |
| Best when | Public or multi-region reads, S3 client code you want to keep | You depend on S3-only features |
Which should you choose? Choose R2 when files are served to people and you do not use the S3-only features above. Choose S3 when you do. If you are undecided, write the code against an S3 client with a configurable endpoint, which is exactly what we did.
How should the storage driver be written so the provider can change?
Write one S3-compatible driver with a configurable endpoint and a local-disk driver for development. In an email-marketing product we designed, the storage layer is one such driver, because R2, Backblaze B2 and MinIO all speak the S3 API, so switching provider is configuration and not code. Staging used local disk; the production provider was left as a recommendation pending the owner’s confirmation (from the project decisions log).
Two details from that design apply to any bucket:
- Key layout carries ownership. Keys are prefixed per tenant account, with a sub-prefix for imports and chat attachments, and a UUID plus the file extension as the name. A lifecycle rule or a deletion job can then target a tenant or a file class by prefix.
- Uploads are never served inline. Import files download with a content disposition and under a sandbox content-security policy, so an uploaded HTML or CSV file cannot execute in the application’s origin.
In the storefront stack, signed uploads to R2 went through aws4fetch, a small AWS Signature V4 fetch wrapper added to the shared site template in October 2026 (from the template’s commit history). It runs where the Web fetch API exists, which includes Workers, and it needs no full SDK.
import { AwsClient } from 'aws4fetch';
const r2 = new AwsClient({
accessKeyId: env.R2_ACCESS_KEY_ID,
secretAccessKey: env.R2_SECRET_ACCESS_KEY,
service: 's3',
region: 'auto',
});
const url = `https://${env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com/${env.R2_BUCKET}/${key}`;
await r2.fetch(url, { method: 'PUT', body, headers: { 'content-type': type } });
How do you serve images from an R2 bucket?
Connect a custom domain to the bucket and serve from that. Cloudflare documents two ways to expose a bucket publicly: a custom domain, and the Cloudflare-managed r2.dev subdomain, which is for non-production use. Public access through r2.dev is rate-limited, and caching, WAF custom rules, access controls and Bot Management are not available there (R2 public buckets).
In practice, each storefront bucket got a custom domain on the brand’s own zone, and the public URL became a configuration value. The setup took two steps: create the bucket, then enable the custom domain so DNS resolves through Cloudflare. The bucket’s settings page offered both options and marked the custom domain as the one for production; we used it for both storefront buckets.
The public URL is also a security boundary, not just a convenience. The storefront backend verifies that a print file URL starts with the configured public URL before it forwards an order to the fulfilment vendor, and refuses the order otherwise (from the project deployment notes). That stops a caller from injecting an arbitrary external file URL into an order.
How do lifecycle rules delete old uploads?
A lifecycle rule scoped to a prefix expires objects after a set number of days. Rules can delete objects, move them from Standard to Infrequent Access, and abort incomplete multipart uploads. Every bucket carries a default rule that expires multipart uploads seven days after initiation, and a bucket supports up to 1,000 rules (R2 object lifecycles).
For customer-uploaded photos on a personalized-print storefront, the rule was scoped to the uploads/ prefix. The documented command for a temporary-upload rule was:
wrangler r2 bucket lifecycle add <bucket> "delete-unconfirmed-uploads-after-7-days" \
"uploads/" --expire-days 7 --abort-multipart-days 1
Two properties of the feature matter in operations. Deletion happens roughly 24 hours after the expiry time, so a seven-day rule is not an exact seven-day guarantee. And if an expire rule and a transition rule collide inside a 24-hour window, the expire rule wins (R2 object lifecycles). If a privacy policy states a retention period, the rule has to be tighter than the promise, not equal to it.
Can R2 hold backups?
Yes, as an S3-compatible target, and the design should not assume it is the only one. A backup script we wrote for a lead-generation platform takes its offsite destination from environment variables: an endpoint, a bucket and a key pair, and any S3-compatible service can fill them. It dumps Postgres in custom format, mirrors object-store buckets to a second local disk, optionally replicates offsite, and enforces 30-day retention both locally and on the offsite bucket (from the script’s header and logic).
That script was written against a self-hosted object store plus an optional offsite endpoint, so R2 is a fit by design, not a deployment we measured. If you use R2 as the offsite copy, two settings follow from the pricing table: keep backups in Standard unless restores are genuinely rare, and use a lifecycle rule for the 30-day expiry instead of a cron job, so retention does not depend on a script that can silently stop running.
What belongs in R2 and what does not?
Customer uploads and large mutable files belong in R2. Small, build-time static files belong with the site. When we moved WordPress sites onto Workers, the pages and their assets shipped with the Worker as static assets, and the routing details are in the run_worker_first post. There was no reason to put a build artifact in a bucket it could be deployed with.
Storage cost is not the only variable: moving files out of a bucket removes the CDN path, which then has to be rebuilt in front of the application. At small volumes, the free tier makes the storage cost close to zero anyway, so a catalogue of static images is not an obvious reason to leave object storage.
What broke and what we changed
The API token could list but not manage lifecycle rules. The backend’s R2 token had object read and write permission only. Reading the lifecycle configuration returned AccessDenied while listing objects worked. The fix was to manage lifecycle rules with a separate, tighter-scoped administrative token and keep the application token to object operations (from the session notes, 2026-10-28).
A single retention rule would have broken two privacy promises. The runbook recommended one 30-day rule on uploads/ for both storefronts. One storefront’s policy promised deletion of unattached uploads within seven days and of order-linked photos 90 days after delivery; the other promised 30 days. One rule would have broken one of the two. The options were separate prefixes per state, so an order-linked photo moves out of the expiring prefix, or separate buckets per store with separate rules (from the project notes, 2026-10-25).
A one-off script saw an empty public URL. A maintenance script inspecting the bucket reported an empty public URL even though the container had the variable set, because the script did not read the environment the way the application did. The bucket name was also exposed under a different variable name than the script expected. The lesson is to name the R2 variables identically in every process that touches the bucket, and to test a diagnostic script against a known value before trusting its empty result (from the session notes, 2026-10-28).
A deploy restarted the whole stack. Because the storefront backend, worker and web containers all needed the five R2 variables, a configuration change deployed all three. We scheduled it away from live verification runs for that reason (from the deployment notes).
Image format limits came from downstream. The fulfilment vendor’s mockup API accepted only jpg, jpeg, png and pdf image URLs, so an image stored as WebP had to be converted before it was sent (from the session notes, 2026-10-26). Storage did not care about the format; the consumer did.
Related
Frequently asked questions
What is Cloudflare R2 used for?
R2 is object storage for files that are written once and read many times: customer uploads, product and editorial images, exports, backups and build artifacts. It speaks the S3 API, so existing S3 clients work against it with a different endpoint. It does not replace a database or a filesystem that an application writes to in place.
How much does Cloudflare R2 cost?
Standard storage is $0.015 per GB-month, Class A operations are $4.50 per million, Class B operations are $0.36 per million, and egress is free. The free tier covers 10 GB-month of storage, 1 million Class A and 10 million Class B operations each month. Infrequent Access storage is $0.01 per GB-month with a $0.01 per GB retrieval fee and a 30-day minimum.
R2 vs S3: which should you use?
Use R2 when files are served to the public or to many regions, because egress is free and the S3 API keeps your client code. Use S3 when you depend on features R2 has not implemented, such as object tagging, versioning, replication or object lock. Check the R2 S3 compatibility page for the current list before committing.
Can you serve images directly from an R2 bucket?
Yes, through a custom domain connected to the bucket. The r2.dev URL also works but is rate-limited and intended for development, and it does not support caching, WAF rules or access controls. For production images, connect a domain you control and let Cloudflare cache it.
How do you automatically delete old uploads from R2?
Add an object lifecycle rule scoped to the prefix the uploads live under, with an expiration in days. Rules can also move objects to Infrequent Access and abort unfinished multipart uploads. Deletion happens around 24 hours after the expiry time, and the API token used to manage rules needs lifecycle permission.
