| | |

Cloudflare 11 ☁️ Cloudflare R2 Object Storage — Serving zero-egress media and files via S3-compatible APIs, presigned URLs, and public buckets

⏱️ Estimated read: 15 min | |

Cloudflare R2 is a globally distributed object storage solution designed to eliminate the most significant pain point of traditional cloud storage: egress fees. In the traditional cloud landscape, providers often lure developers with low storage costs only to charge exorbitant fees when that data is actually retrieved or moved. R2 disrupts this model by offering zero-egress storage, allowing developers to store and access large volumes of data—such as images, videos, logs, and application backups—without worrying about a fluctuating “egress tax.” Built on top of Cloudflare’s global edge network, R2 provides high durability and low-latency access by being physically closer to the end-users who request the data.

Because R2 is built with S3-compatibility in mind, it allows for a seamless transition for applications already using the Amazon S3 API. Developers can use existing libraries, SDKs, and CLI tools with minimal configuration changes. However, R2 is not just a passive storage bin; it is deeply integrated with the Cloudflare ecosystem, particularly Cloudflare Workers. This integration allows for a “Serverless Storage” paradigm where logic can be executed at the edge to transform, filter, or authorize data access before it ever leaves Cloudflare’s network. This makes R2 an ideal choice for modern web applications that require high performance and predictable costs.

This chapter provides a comprehensive deep dive into the architecture and implementation of Cloudflare R2. We will explore the mechanics of the S3-compatible API, the nuances of bucket management, and the security models governing data access. We will also examine the different methods for serving data, including public buckets for open assets and presigned URLs for temporary, authenticated access. Finally, we will look at how to bind R2 buckets to Cloudflare Workers to create powerful, edge-driven data processing pipelines.

The sections that follow cover the S3-compatibility layer and authentication, the implementation of presigned URLs and public access, and the integration of R2 with the Cloudflare Workers runtime.

Key point: Cloudflare R2’s primary value proposition is the total elimination of egress fees, combined with S3 API compatibility and deep integration with the Cloudflare Workers edge runtime for low-latency, programmatic data access.


Why exists

The egress tax problem. Traditional cloud storage providers like AWS, Azure, and Google Cloud have historically used egress fees as a form of vendor lock-in. While it is inexpensive to put data in, it is prohibitively expensive to take it out. This creates a financial barrier for businesses that want to multi-cloud or move their data to a more specialized processing service. R2 exists to break this cycle by making data movement financially neutral.

The latency of centralized storage. Centralized object storage often resides in a few specific geographic regions. When a user in Singapore requests an image stored in a US-East region, the data must travel across the globe, leading to high latency. R2 leverages Cloudflare’s edge network to cache and serve content closer to the user, significantly reducing the Time to First Byte (TTFB) for static assets.

The complexity of serverless data. Traditional serverless functions often struggle with data persistence. Connecting a serverless function to a centralized database or storage bucket often introduces cold-start latencies and connection overhead. R2, when bound to Workers, provides an “Edge-Native” storage solution where the compute and the storage share the same infrastructure, minimizing the overhead of data retrieval.

The cost predictability challenge. For many startups and enterprises, egress fees represent an “unknown” variable in the monthly budget. A sudden spike in traffic or a viral video can lead to thousands of dollars in unexpected bandwidth charges. R2 simplifies the billing model by charging only for the volume of data stored and the number of operations performed (Class A and Class B), removing the bandwidth variable entirely.

The vendor lock-in trade-off. Developers often hesitate to move away from S3 because of the massive ecosystem of tools built around it. Cloudflare recognized this and designed R2 to be S3-compatible. This means you can keep your existing deployment scripts, backup tools, and SDKs while switching the underlying storage provider to one that doesn’t charge for data retrieval.

The need for programmatic storage. Sometimes, data shouldn’t just be “served”; it should be “processed.” R2 exists to facilitate workflows where a Worker can intercept a request, check a user’s subscription status in a KV store, and then dynamically pull a file from R2, perhaps resizing an image or watermarking a PDF on the fly before sending it to the client.


a. S3 Compatibility and Bucket Management

Cloudflare R2 is designed to be a drop-in replacement for Amazon S3 for most common use cases. It supports the core S3 API actions, including PutObject, GetObject, ListObjectsV2, and DeleteObject. This compatibility is achieved through an S3 API endpoint provided for each R2 account. To interact with R2 using standard S3 tools (like the AWS SDK or rclone), you simply need to point the service’s custom endpoint to your R2 account ID and provide your R2 API credentials (Access Key ID and Secret Access Key).

// Example: Initializing the AWS SDK v3 for R2 compatibility
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";

const s3Client = new S3Client({
  region: "auto", // R2 uses 'auto' as it is globally distributed
  endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
  credentials: {
    accessKeyId: process.env.R2_ACCESS_KEY_ID,
    secretAccessKey: process.env.R2_SECRET_ACCESS_KEY,
  },
});

The “Bucket” is the fundamental unit of organization in R2. A bucket is a container for objects (files). Unlike a traditional file system, R2 is a flat structure; however, you can simulate directories using prefixes in the object keys (e.g., uploads/images/photo.jpg). Managing buckets can be done through the Cloudflare Dashboard, the wrangler CLI, or programmatically via the S3 API.

When choosing a bucket name, it is important to remember that R2 bucket names are scoped to your account, not globally across all Cloudflare users (unlike S3). This makes naming much easier as you don’t have to fight for “my-images” if someone else has already taken it. However, the bucket names must still follow standard naming conventions (lowercase letters, numbers, and hyphens).

# Using Wrangler to create a bucket
npx wrangler r2 bucket create my-media-bucket

# Listing buckets
npx wrangler r2 bucket list

Data in R2 is eventually consistent for metadata operations but provides strong consistency for read-after-write operations on a per-object basis. This means if you upload a file and immediately request it, you are guaranteed to get the latest version. However, if you list the objects in a bucket immediately after a delete, the deleted object might still appear in the list for a short window.


b. Access Patterns: Public Buckets and Presigned URLs

R2 offers several ways to serve data to end-users, depending on the security requirements of the assets. The simplest method is the Public Bucket. By connecting a custom domain or a r2.dev subdomain to a bucket, you can make its contents accessible to the entire internet. This is ideal for public website assets like CSS, JavaScript, and public-facing images.

To enable a public bucket, you navigate to the bucket settings in the dashboard and “Allow Access.” You can then link a domain you manage on Cloudflare to that bucket. This automatically handles SSL/TLS and allows you to use Cloudflare’s Cache and WAF features in front of your storage.

// Public URL structure (if custom domain is configured)
https://assets.example.com/logo.png -> maps to 'logo.png' in R2 bucket

For private data that should only be accessible temporarily or to specific users, Presigned URLs are the industry standard. A presigned URL is a specialized URL that includes authentication information in the query string. It allows a user to perform a specific action (like GET to download or PUT to upload) for a limited period, even if the bucket itself is private.

// Generating a Presigned URL for downloading (GET) using AWS SDK v3
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { GetObjectCommand } from "@aws-sdk/client-s3";

const command = new GetObjectCommand({
  Bucket: "my-private-bucket",
  Key: "user-report.pdf",
});

// URL expires in 3600 seconds (1 hour)
const url = await getSignedUrl(s3Client, command, { expiresIn: 3600 });
console.log(`Access the file here: ${url}`);

Presigned URLs are generated locally by your server or Worker using your secret keys; no network call to Cloudflare is required to generate the URL itself. This makes them extremely efficient for generating thousands of unique download links for a dashboard or secure upload links for a user profile picture. Once the expiresIn time passes, the URL becomes invalid, and R2 will reject the request with a 403 Forbidden error.


c. Programmatic Control with Workers Integration

The most powerful way to use R2 is by binding it directly to a Cloudflare Worker. This bypasses the S3 API entirely and uses a native, high-performance internal API. When a bucket is bound to a Worker, it is exposed as an object on the global env variable. This allows the Worker to read, write, and delete objects with extremely low latency.

The Worker acts as a gatekeeper. Instead of making a bucket public, you can keep it private and use a Worker to handle requests. The Worker can check an Authorization header, validate a JWT, or check a database before deciding whether to serve the file from R2.

// Example: Serving an object via a Worker binding
export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const key = url.pathname.slice(1); // Remove leading slash

    // Attempt to retrieve the object from the bound R2 bucket
    const object = await env.MY_BUCKET.get(key);

    if (object === null) {
      return new Response("Object Not Found", { status: 404 });
    }

    // Set appropriate headers and return the object body
    const headers = new Headers();
    object.writeHttpMetadata(headers);
    headers.set("etag", object.httpEtag);

    return new Response(object.body, { headers });
  },
};

Beyond simple serving, Workers can manipulate data on the fly. For example, a Worker can receive an upload, calculate its hash, store the metadata in a KV store, and then save the file to R2. Or, it can implement a “Smart CDN” that looks for a requested image in R2; if it doesn’t exist, it pulls it from an legacy origin, saves a copy to R2, and then returns it to the user.

Binding a bucket to a Worker is done in the wrangler.toml configuration file. This creates a link between the variable name used in your code and the actual bucket name in your Cloudflare account.

# wrangler.toml
[[r2_buckets]]
binding = "MY_BUCKET"
bucket_name = "production-assets-bucket"

Complete Example Session

// ============================================
// PART 1: WRANGLER CONFIGURATION
// ============================================
// wrangler.toml
// [[r2_buckets]]
// binding = "REPORTS_BUCKET"
// bucket_name = "user-reports-prod"

// ============================================
// PART 2: THE WORKER SCRIPT (ES MODULES)
// ============================================
export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const method = request.method;
    const path = url.pathname;

    // ============================================
    // PART 3: AUTHENTICATION CHECK
    // ============================================
    const authHeader = request.headers.get("Authorization");
    if (authHeader !== "Bearer secret-token") {
      return new Response("Unauthorized", { status: 401 });
    }

    // ============================================
    // PART 4: HANDLING UPLOADS (PUT)
    // ============================================
    if (method === "PUT" && path.startsWith("/upload/")) {
      const filename = path.replace("/upload/", "");
      const content = await request.arrayBuffer();
    
      await env.REPORTS_BUCKET.put(filename, content, {
        httpMetadata: { contentType: "application/pdf" },
        customMetadata: { uploadedBy: "System" }
      });
    
      return new Response(`Uploaded ${filename}`, { status: 201 });
    }

    // ============================================
    // PART 5: HANDLING DOWNLOADS (GET)
    // ============================================
    if (method === "GET" && path.startsWith("/download/")) {
      const filename = path.replace("/download/", "");
      const object = await env.REPORTS_BUCKET.get(filename);

      if (!object) return new Response("Not Found", { status: 404 });

      const headers = new Headers();
      object.writeHttpMetadata(headers);
      headers.set("etag", object.httpEtag);
      return new Response(object.body, { headers });
    }

    // ============================================
    // PART 6: LISTING OBJECTS
    // ============================================
    if (method === "GET" && path === "/list") {
      const list = await env.REPORTS_BUCKET.list();
      const keys = list.objects.map(obj => obj.key);
      return Response.json(keys);
    }

    // ============================================
    // PART 7: CONDITIONAL GET (ETAGS)
    // ============================================
    if (method === "GET" && path.startsWith("/cached/")) {
      const key = path.replace("/cached/", "");
      const object = await env.REPORTS_BUCKET.get(key, {
        onlyIf: request.headers,
      });
      if (!object) return new Response(null, { status: 304 });
      return new Response(object.body);
    }

    // ============================================
    // PART 8: DELETING OBJECTS
    // ============================================
    if (method === "DELETE" && path.startsWith("/delete/")) {
      const key = path.replace("/delete/", "");
      await env.REPORTS_BUCKET.delete(key);
      return new Response("Deleted", { status: 200 });
    }

    // ============================================
    // PART 9: HEAD REQUESTS (METADATA ONLY)
    // ============================================
    if (method === "HEAD" && path.startsWith("/meta/")) {
      const key = path.replace("/meta/", "");
      const object = await env.REPORTS_BUCKET.head(key);
      if (!object) return new Response("Not Found", { status: 404 });
      return new Response(null, { headers: { "X-Size": object.size.toString() } });
    }

    return new Response("Method Not Allowed", { status: 405 });
  }
};

// ============================================
// PART 10: SUMMARY OF CAPABILITIES
// ============================================

The example above demonstrated the full lifecycle of R2 management inside a Worker: authentication, uploading content with metadata, retrieving content with HTTP headers, listing bucket keys, using Etags for caching, deleting objects, and performing HEAD requests for metadata retrieval.


Quick Reference

R2 Pricing Components

ComponentCostNotes
Egress (Bandwidth)$0.00The primary differentiator of R2
Storage$0.015 / GB-monthFirst 10GB usually free
Class A Ops (Write)$4.50 / millionMutating operations (PUT, List)
Class B Ops (Read)$0.36 / millionNon-mutating operations (GET, HEAD)

Worker R2 Methods (Native API)

MethodDescriptionReturn Type
get(key, options?)Retrieves object and body`Promise<R2ObjectBody
head(key)Retrieves metadata only`Promise<R2Object
put(key, val, options?)Creates/Updates an objectPromise<R2Object>
delete(key)Removes an objectPromise<void>
list(options?)Lists objects in bucketPromise<R2Objects>

Common S3 API Translations

FeatureS3 StandardR2 Standard
Regionus-east-1, etc.auto
Endpoints3.amazonaws.com<account_id>.r2.cloudflarestorage.com
ConsistencyStrong (most regions)Strong (read-after-write)
Bucket ScopingGlobalAccount-level

Best Practices

✅ Do This:

// Use 'auto' for the region in S3 clients
const client = new S3Client({ region: "auto", ... });          // ✅

// Leverage 'writeHttpMetadata' to simplify header management
object.writeHttpMetadata(headers);                             // ✅

// Use prefixes to simulate folders for organization
const key = `users/${userId}/profile.png`;                     // ✅

// Always check for null when using 'get' or 'head'
if (object === null) { /* handle 404 */ }                     // ✅

// Use Presigned URLs for browser-based direct uploads
const url = await getSignedUrl(client, putCommand, { ... });   // ✅

❌ Don’t Do This:

// Don't hardcode Secret Keys in your Worker code
const secret = "MY_AWS_SECRET"; // Use env variables!        // ❌

// Don't make a bucket public if it contains sensitive data
// (Use a Worker gatekeeper instead)                          // ❌

// Don't use R2 for data that changes many times per second
// (Use KV or Durable Objects for that)                       // ❌

// Don't forget to set 'contentType' during 'put'
// (Otherwise it defaults to binary/octet-stream)             // ❌

Common Pitfalls

PitfallWhy It HappensFix
403 Invalid SignatureClock skew or wrong Account ID in URLEnsure system time is synced; double-check Endpoint URL
High Class A Ops CostsFrequent listing or small overwritesCache list results; use KV for metadata tracking
Missing CORS headersBrowser security blocks direct R2 fetchConfigure CORS settings in the R2 Dashboard
Wrong Region ErrorUsing AWS region like us-east-1Always use auto for Cloudflare R2
File not updatingBrowser/CDN cache is too aggressiveUse Etags or cache-busting query params
404 on Worker bindingTypo in wrangler.toml or dashboardVerify binding name matches env.NAME exactly

Real-World Examples

1. Public Asset Hosting

Serving site images via https://cdn.example.com/ linked directly to an R2 bucket.

2. Secure User Uploads

Generating a 5-minute Presigned PUT URL so a user can upload a file directly to R2 from their browser.

3. Database Backups

A cron-job script using the S3 API to push nightly database dumps to R2 for long-term, zero-cost storage.

4. Image Resizing Proxy

A Worker that pulls an original image from R2, resizes it using Cloudflare Images, and returns it.

5. Log Aggregation

Appending small log chunks to R2 (using standard PUT) for later batch processing.

6. Video Streaming Origin

Serving HLS video segments from R2, benefiting from zero egress as they flow through the CDN.

7. Build Artifact Storage

CI/CD pipelines pushing .zip or .tar.gz build outputs to a private R2 bucket.

8. Large Data Migration

Using rclone to move terabytes of data from AWS S3 to R2 to stop paying egress fees.

9. Programmatic PDF Generation

A Worker generating a PDF invoice and saving it to R2 before emailing the link to a user.

10. Multi-tenant File Storage

Using prefixes (e.g., tenant_id/file_name) to isolate data for different customers in a single bucket.


Visual

The Zero-Egress Data Flow

┌──────────────────────────────────────────────────────────┐
│  DATA RETRIEVAL PATHWAY                                  │
│                                                          │
│  [ User ] ──────────┐                                    │
│                     │ 1. Request file.jpg                │
│                     ▼                                    │
│  ┌────────────────────────────────────────────────────┐  │
│  │  CLOUDFLARE EDGE (Worker / CDN)                    │  │
│  │                                                    │  │
│  │  2. Internal API Fetch (Zero Latency Overhead)     │  │
│  └──────────┬─────────────────────────────────────────┘  │
│             │                                            │
│             ▼                                            │
│  ┌────────────────────────────────────────────────────┐  │
│  │  CLOUDFLARE R2 STORAGE                             │  │
│  │                                                    │  │
│  │  3. Retrieve Object ──► 0$ Egress Fee to Cloudflare│  │
│  └──────────┬─────────────────────────────────────────┘  │
│             │                                            │
│             ▼                                            │
│  [ User ] ◄─┘ 4. Receive File (No bandwidth cost)        │
└──────────────────────────────────────────────────────────┘

Presigned URL Authentication Flow

┌──────────────────────────────────────────────────────────┐
│  PRESIGNED URL LIFECYCLE                                 │
│                                                          │
│  1. [ App Server ] ─── Auth ───► [ Cloudflare R2 ]       │
│     (Has Secrets)         (Local generation of Sig)      │
│                                                          │
│  2. [ App Server ] ─── URL ────► [ Client Browser ]      │
│     (https://.../key?sig=xyz)                            │
│                                                          │
│  3. [ Client Browser ] ── GET ─► [ Cloudflare R2 ]       │
│     (Within Expiration window)                           │
│                                                          │
│  4. [ Cloudflare R2 ] ─ File ──► [ Client Browser ]      │
│     (Access Granted based on Sig)                        │
└──────────────────────────────────────────────────────────┘

Worker-to-R2 Native Binding

┌──────────────────────────────────────────────────────────┐
│  WORKER BINDING ARCHITECTURE                             │
│                                                          │
│  worker.js:                                              │
│  ┌────────────────────────────────────────────────────┐  │
│  │                                                    │  │
│  │  export default {                                  │  │
│  │    async fetch(req, env) {                         │  │
│  │      const obj = await env.MY_BUCKET.get('key');   │  │
│  │      return new Response(obj.body);                │  │
│  │    }                                               │  │
│  │  }                                                 │  │
│  │                                                    │  │
│  └───────────────────┬────────────────────────────────┘  │
│                      │                                   │
│                      ▼                                   │
│  ┌────────────────────────────────────────────────────┐  │
│  │  R2 STORAGE ENGINE                                 │  │
│  │  (Shared infrastructure, fast internal path)       │  │
│  └────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────┘

Summary

ItemValue
Primary FeatureZero Egress Fees
API InterfaceS3-Compatible + Native Workers API
Storage Cost$0.015 per GB-month
ConsistencyStrong read-after-write for objects
ScalingGlobally distributed, high durability
Worker Binding[[r2_buckets]] in wrangler.toml
SecurityAPI Keys (S3) or Worker Logic
Regional SettingAlways use auto

Key takeaways:

  • R2 removes the egress fee barrier. You are charged only for storage and operations (PUT/GET), not for the bandwidth used when your users download your content.
  • S3 compatibility ensures a low barrier to entry. You can use the AWS SDK, rclone, or any S3-compatible tool by simply changing the endpoint and credentials.
  • Workers integration is the “superpower” of R2. Binding a bucket to a Worker allows for high-performance, programmatic access where the compute happens at the edge alongside the storage.
  • Presigned URLs handle temporary, secure access. They allow private objects to be downloaded or uploaded by unauthenticated clients for a specific window of time without exposing secret keys.
  • Public buckets simplify static asset delivery. Connecting a domain to a bucket turns R2 into a globally distributed, CDN-backed file host with minimal configuration.

Remember: Cloudflare R2 is the logical choice for any application where data retrieval costs are a concern. By combining zero egress with S3 compatibility and edge-compute integration, it provides a flexible, cost-effective, and high-performance storage layer for the modern web.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!