Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 36 ยท Storage: R2, KV and D1

Cloudflare R2: S3-Compatible Object Storage

Store files in Cloudflare R2: create buckets, upload and download through a Worker binding or the S3 API, set metadata, list by prefix, serve public files and understand pricing.

R2 is Cloudflare's object storage. An object is a file (any bytes) stored under a key inside a bucket. You use it for images, videos, documents, backups, logs and build artifacts. R2 speaks the same API as Amazon S3, so existing tools and SDKs work with it, and its headline feature is that reading data out of R2 costs no egress fee, which is often the largest line on a storage bill.

R2 is not available on this site: commands and Worker code below are read-only. The runnable examples simulate the object API in memory so you can practice the patterns.

Buckets and keys

A bucket is a flat namespace of keys. There are no real folders: a key like avatars/42/photo.jpg simply contains slashes, and tools display it as a folder. Create a bucket from the dashboard or Wrangler:

Terminal
npx wrangler r2 bucket create my-uploads
npx wrangler r2 object put my-uploads/hello.txt --file ./hello.txt
npx wrangler r2 object get my-uploads/hello.txt
npx wrangler r2 bucket list

Bind it to a Worker in wrangler.jsonc:

JSONC
{ "r2_buckets": [{ "binding": "UPLOADS", "bucket_name": "my-uploads" }] }

The Worker API

JavaScript
export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const key = url.pathname.slice(1);                 // "avatars/42.png"

    if (request.method === "PUT") {
      await env.UPLOADS.put(key, request.body, {
        httpMetadata: { contentType: request.headers.get("content-type") },
        customMetadata: { uploadedBy: "user-42" },
      });
      return new Response("stored", { status: 201 });
    }

    if (request.method === "GET") {
      const object = await env.UPLOADS.get(key);
      if (object === null) return new Response("Not found", { status: 404 });
      const headers = new Headers();
      object.writeHttpMetadata(headers);               // content-type, cache-control, ...
      headers.set("etag", object.httpEtag);
      return new Response(object.body, { headers });
    }

    if (request.method === "DELETE") {
      await env.UPLOADS.delete(key);
      return new Response(null, { status: 204 });
    }

    if (request.method === "HEAD") {
      const meta = await env.UPLOADS.head(key);        // metadata only, no body
      return new Response(null, { status: meta ? 200 : 404 });
    }

    return new Response("Method not allowed", { status: 405 });
  },
};

Methods to know: put, get, head, delete (also an array of keys), list (with prefix, delimiter, cursor, limit) and multipart upload for very large files. get returns null when the key does not exist; the returned object has body (a stream), size, etag, uploaded, httpMetadata and customMetadata.

Streaming matters: request.body and object.body are streams, so a Worker can move a huge file without holding it in memory.

An object-storage stand-in

JS In-memory bucket with prefixes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The delimiter listing is how a file browser shows folders: objects directly under the prefix, plus a list of "subfolder" prefixes.

Using the S3 API

Because R2 is S3-compatible, you can use the AWS SDK, rclone or aws s3 from outside Cloudflare. Create an R2 API token (access key id and secret) and point the client at your account's endpoint, https://<account-id>.r2.cloudflarestorage.com, with region auto:

JavaScript
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";

const s3 = new S3Client({
  region: "auto",
  endpoint: `https://${process.env.CF_ACCOUNT_ID}.r2.cloudflarestorage.com`,
  credentials: { accessKeyId: process.env.R2_KEY, secretAccessKey: process.env.R2_SECRET },
});
await s3.send(new PutObjectCommand({ Bucket: "my-uploads", Key: "a.txt", Body: "hi" }));

Presigned URLs (made with that same SDK) let a browser upload or download directly to R2 for a limited time without exposing your credentials; the file bytes never pass through your Worker.

Serving files publicly

Buckets are private by default. Three ways to make objects readable:

  1. Through a Worker (shown above) when you need checks such as login or resizing.
  2. A custom domain attached to the bucket (for example files.example.com), which also lets Cloudflare cache objects at the edge.
  3. The r2.dev public URL, which is rate limited and meant for testing, not production.

Set Cache-Control on objects (httpMetadata.cacheControl) so the edge cache and browsers can keep them.

Pricing model

R2 charges for stored data (per GB-month) and for operations, split into Class A (writes, lists) and Class B (reads); there is a free monthly allowance, and egress is free. There is also an Infrequent Access storage class for rarely read data, which stores cheaper but charges a retrieval fee. Prices change, so confirm them on Cloudflare's pricing page; this estimator uses example numbers only.

JS R2 bill estimator (example prices)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Practical tips

  • Use meaningful keys with prefixes (user/42/avatar.png), and avoid millions of objects with one flat unsorted prefix when you plan to list them.
  • Store the content type on upload, or browsers will not render files correctly.
  • Enable lifecycle rules to expire temporary uploads automatically.
  • Keep object metadata (owner, status) in D1 so you can query it; R2 has no query language.
  • Treat keys like paths: validate and normalize any user-supplied key to stop one user overwriting another's files.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is R2's best-known pricing advantage over many object stores?

    R2 charges for storage and operations but not for egress bandwidth, which is often the biggest cost with other providers.
  2. 2. How are 'folders' represented in a bucket?

    A bucket is flat. A key such as a/b/c.txt only looks like a path; list with prefix and delimiter to simulate folders.
  3. 3. What does env.UPLOADS.get('missing-key') return?

    get resolves to null if the object does not exist.
  4. 4. You want browsers to upload large files without passing through your Worker. What do you use?

    A presigned URL grants temporary access straight to R2, so the bytes never pass through your code.

Summary

  • R2 stores objects (files) under keys in buckets; it speaks the S3 API and has no egress fees.
  • Workers use a bucket binding: put, get, head, delete, list; bodies are streams.
  • Buckets are private; serve through a Worker, a custom domain, or (for tests) r2.dev; use presigned URLs for direct uploads.
  • You pay for stored data and operations; keep queryable metadata in D1.

Next: D1: A Serverless SQL Database