← Back to dashboard
cloudflare-r2hostingfreshReader view (for NotebookLM)

Cloudflare R2 (Private Media Storage) Integration Guide

Keeping media private on R2

The real model

Private bucket + server-minted presigned URLs or a Worker gate. Sign the headers you validate.

Use @aws-sdk/client-s3 3.1153.0 against https://<ACCOUNT_ID>.r2.cloudflarestorage.com (or <id>.<eu|us|fedramp>.r2... for jurisdictional buckets) with region 'auto'. Two current-SDK traps. First, the presigner leaves content-type unsigned unless you pass signableHeaders: new Set(['content-type']); add ContentLength to the PutObjectCommand to sign the exact size too. Second, since 3.729 default checksums bake an empty-body CRC32 into presigned PUT URLs, so set requestChecksumCalculation: 'WHEN_REQUIRED'. In a Worker, bind the bucket (env.MEDIA.get/put/delete/list; type Env with `wrangler types`), authorize first, and map a failed onlyIf to 304. Wrangler 4.151's `r2 object put` writes to LOCAL storage unless you pass --remote. For codeAmani: thumbs.codeamanilabs.org is the only public bucket. User media stays private, keyed by Clerk userId, with TTLs measured in minutes. The new `us` jurisdiction gives US residency, but you can't change it later.

Six R2 access primitives

Buckets start locked. These are the tools for handing out scoped, temporary access without ever exposing your keys.

Text
 ██████╗██╗      ██████╗ ██╗   ██╗██████╗ ███████╗██╗      █████╗ ██████╗ ███████╗    ██████╗ ██████╗
██╔════╝██║     ██╔═══██╗██║   ██║██╔══██╗██╔════╝██║     ██╔══██╗██╔══██╗██╔════╝    ██╔══██╗╚════██╗
██║     ██║     ██║   ██║██║   ██║██║  ██║█████╗  ██║     ███████║██████╔╝█████╗      ██████╔╝ █████╔╝
██║     ██║     ██║   ██║██║   ██║██║  ██║██╔══╝  ██║     ██╔══██║██╔══██╗██╔══╝      ██╔══██╗██╔═══╝
╚██████╗███████╗╚██████╔╝╚██████╔╝██████╔╝██║     ███████╗██║  ██║██║  ██║███████╗    ██║  ██║███████╗
 ╚═════╝╚══════╝ ╚═════╝  ╚═════╝ ╚═════╝ ╚═╝     ╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝    ╚═╝  ╚═╝╚══════╝

Cloudflare R2 (Private Media Storage) Integration Guide

Focus: storing user-uploaded media (images, receipts, ID documents, audio) in Cloudflare R2 so it stays private: private buckets, server-minted presigned URLs, Worker-gated access, and direct-to-R2 browser uploads that never expose your credentials. Also covers the rest of the R2 surface: CORS, lifecycle rules, event notifications, storage classes, jurisdictions, migrations, and the Basin (formerly R2 Data Catalog / R2 SQL) analytics layer.

Overview

Cloudflare R2 is S3-compatible object storage with zero egress fees. You pay for storage and for operations, not for bytes served out (via the S3 API, the Workers API, or r2.dev). It exposes three interfaces:

InterfaceUse it fromAuth
S3-compatible API (https://<ACCOUNT_ID>.r2.cloudflarestorage.com)Next.js routes, scripts, any AWS SDKR2 API token (Access Key ID + Secret), or temporary credentials
Workers binding (env.MY_BUCKET.get/put/delete/list)Code running inside a Cloudflare WorkerThe binding itself; no keys
Public bucket (custom domain or r2.dev)Browsers, CDNsNone (public), or WAF / Access rules on a custom domain

The security headline: buckets are private by default. Nothing is reachable from the Internet until you attach a custom domain or enable the r2.dev URL. For private media you keep it that way and hand out temporary, scoped access.

Versions (verified 2026-10-20)

Package / toolVersionNotes
@aws-sdk/client-s33.1153.0Default checksum behavior changed in 3.729.0; see Checksums
@aws-sdk/s3-request-presigner3.1153.0Keep in lockstep with client-s3
@cloudflare/workers-types5.20261019.1Now major 5. Cloudflare recommends npx wrangler types to generate Env + runtime types instead
wrangler4.151.2Needs Node.js 22+

Official Documentation


The privacy model (read this first)

Six rules that keep media private:

  1. Leave the bucket private. Don't enable public access for user data. A public bucket means anyone with the URL can read the object, for as long as access stays enabled.
  2. Credentials are server-only. S3 keys and Worker secrets live in server env or Wrangler secrets. They never go in client JS or NEXT_PUBLIC_*.
  3. Hand out short-lived capability URLs. Presigned URLs live from 1 second to 7 days (604,800 s). Treat them as bearer tokens: they're reusable until they expire, not single-use. Keep TTLs to minutes.
  4. Actually sign what you validate. Pass signableHeaders: new Set(["content-type"]) to getSignedUrl. Without it, the presigner leaves Content-Type out of the signature (see Pattern B).
  5. r2.dev is for development only. It's rate-limited (hundreds of requests per second, then 429) and has no WAF, cache, Access or Bot Management. Production goes behind a custom domain or a Worker.
  6. Scope tokens. Use Object Read only or Object Read & Write tokens scoped to one bucket. Keep Admin tokens for bucket configuration. For per-user delegation, mint temporary credentials scoped to a prefix.

Setup

S3 credentials

Create an R2 API token in the dashboard (R2 > Manage API Tokens). Pick Account tokens for services and User tokens for personal tooling. You get an Access Key ID and a Secret Access Key. The token permissions are:

PermissionAllows
Admin Read & WriteCreate, list and delete buckets; edit bucket config (CORS, lifecycle, locks); read and write objects; read and write Basin Catalog
Admin Read onlyList buckets, view config, read and list objects, read Basin Catalog
Object Read & WriteRead, write and list objects in specific buckets (S3 API only)
Object Read onlyRead and list objects in specific buckets (S3 API only)
Bash
npm install @aws-sdk/client-s3@3.1153.0 @aws-sdk/s3-request-presigner@3.1153.0
TypeScript
// lib/r2.ts — server-only client. Never import this into client components.
import { S3Client } from "@aws-sdk/client-s3";

export const r2 = new S3Client({
  region: "auto", // required by the SDK, ignored by R2
  endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
  // For a jurisdictional bucket: https://<ACCOUNT_ID>.<eu|us|fedramp>.r2.cloudflarestorage.com
  credentials: {
    accessKeyId: process.env.R2_ACCESS_KEY_ID!,
    secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
  },
  // Opt out of the SDK's default flexible checksums (see "Checksums" below).
  requestChecksumCalculation: "WHEN_REQUIRED",
  responseChecksumValidation: "WHEN_REQUIRED",
});

export const R2_BUCKET = process.env.R2_BUCKET!;

examples/r2-client.ts is the hardened version, with env validation and a jurisdiction-aware endpoint.

Checksums and the AWS SDK v3

Since @aws-sdk/client-s3 3.729.0, requestChecksumCalculation and responseChecksumValidation default to "WHEN_SUPPORTED". Against R2 that means:

  • Direct PutObject / UploadPart calls send CRC32 checksum headers. R2 supports CRC32, CRC32C, SHA-1, SHA-256 (composite) and CRC64NVME (full-object, since 2025-07-03), so direct calls generally work. R2 rejects a mismatch with BadDigest (400, error code 10037).
  • Presigned PUT URLs (verified on 3.1153.0) get x-amz-checksum-crc32=AAAAAA== and x-amz-sdk-checksum-algorithm=CRC32 baked into the query string. AAAAAA== is the CRC32 of an empty body, computed when the URL is signed and not when the file is uploaded.
  • Presigned GET URLs get x-amz-checksum-mode=ENABLED. R2's own example URLs include this parameter, and it's harmless.

Set both options to "WHEN_REQUIRED" on any client that mints presigned URLs. You can also use the env vars AWS_REQUEST_CHECKSUM_CALCULATION and AWS_RESPONSE_CHECKSUM_VALIDATION. Upload integrity then comes from the signed Content-Length, an ETag check, or a checksum you compute and send yourself.


Pattern A: Presigned download URL (time-boxed read)

Mint a short-lived GET URL on the server and hand it to the authenticated user. Keys contain / (userId/uuid.ext), so use a catch-all segment. In Next.js 15+, params is a Promise.

TypeScript
// app/api/media/[...key]/route.ts
import { GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { auth } from "@clerk/nextjs/server";
import { NextRequest, NextResponse } from "next/server";
import { r2, R2_BUCKET } from "@/lib/r2";

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ key: string[] }> },
) {
  const { userId } = await auth();
  if (!userId) return new NextResponse("Unauthorized", { status: 401 });

  const key = (await params).key.join("/");
  // Authorize: users may only read their own namespace (or look up an ACL in your DB).
  if (!key.startsWith(`${userId}/`)) {
    return new NextResponse("Forbidden", { status: 403 });
  }

  const url = await getSignedUrl(
    r2,
    new GetObjectCommand({ Bucket: R2_BUCKET, Key: key }),
    { expiresIn: 300 }, // 5 minutes; re-mint on demand
  );
  return NextResponse.redirect(url);
}

Pattern B: Presigned upload URL (direct browser to R2)

The browser uploads straight to R2 with a presigned PUT, so the bytes never pass through your server. Two settings decide whether the URL enforces what you validated:

  • signableHeaders: new Set(["content-type"]). @aws-sdk/s3-request-presigner adds content-type to its unsignable headers by default. Without this option, X-Amz-SignedHeaders is just host, and the client can PUT any type under your key.
  • ContentLength. With signableHeaders set, the declared length is signed too (content-length;content-type;host). The upload must then be exactly that many bytes, which makes it your size cap.
TypeScript
// app/api/uploads/route.ts — returns a short-lived PUT URL
import { PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { auth } from "@clerk/nextjs/server";
import { NextRequest, NextResponse } from "next/server";
import { r2, R2_BUCKET } from "@/lib/r2";

const EXT: Record<string, string> = { "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp" };
const MAX_BYTES = 10 * 1024 * 1024;

export async function POST(req: NextRequest) {
  const { userId } = await auth();
  if (!userId) return new NextResponse("Unauthorized", { status: 401 });

  const { contentType, size } = (await req.json()) as { contentType: string; size: number };
  const ext = EXT[contentType];
  if (!ext) return new NextResponse("Unsupported media type", { status: 415 });
  if (!Number.isInteger(size) || size <= 0 || size > MAX_BYTES) {
    return new NextResponse("Too large", { status: 413 });
  }

  // Namespace by user; never trust the client filename in the key.
  const key = `${userId}/${crypto.randomUUID()}${ext}`;
  const uploadUrl = await getSignedUrl(
    r2,
    new PutObjectCommand({ Bucket: R2_BUCKET, Key: key, ContentType: contentType, ContentLength: size }),
    { expiresIn: 120, signableHeaders: new Set(["content-type"]) },
  );
  return NextResponse.json({ uploadUrl, key });
}
TypeScript
// client: the PUT must send the SAME Content-Type; the browser sets Content-Length from the File
export async function uploadFile(file: File): Promise<string> {
  const res = await fetch("/api/uploads", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ contentType: file.type, size: file.size }),
  });
  if (!res.ok) throw new Error(`Upload rejected: ${res.status}`);
  const { uploadUrl, key } = (await res.json()) as { uploadUrl: string; key: string };

  const put = await fetch(uploadUrl, { method: "PUT", headers: { "Content-Type": file.type }, body: file });
  if (!put.ok) throw new Error(`R2 PUT failed: ${put.status}`);
  return key;
}

Browser uploads need CORS on the bucket. Allow PUT from your origin with AllowedHeaders: ["Content-Type"] (see CORS). R2 sends no CORS headers on a 403 ExpiredRequest, so browser JS can't read an expiry error. Mint a fresh URL before every upload.

Presigned POST (HTML form uploads) is not supported. R2 supports presigned GET, HEAD, PUT and DELETE.

Pattern T: Temporary credentials (scoped S3 session)

Use temporary credentials when a caller needs several S3 operations: a mobile app listing and reading its own prefix, or a multipart upload. They're short-lived and derived from a parent R2 API token. Each one is bound to one bucket, a permission scope (object-read-only, object-read-write, admin-read-only or admin-read-write), and optional prefixes and objects.

  • Mint them with the Temporary Credentials API, or locally by signing a JWT with the parent secret. Restricting by S3 action (actions: ["GetObject", "HeadObject"]) works only with local signing.
  • Use them by passing accessKeyId, secretAccessKey and sessionToken to the SDK. The session token travels in X-Amz-Security-Token.
  • Revoke them by revoking the parent token. A credential can't exceed its parent's permissions.
TypeScript
import { S3Client, type S3ClientConfig } from "@aws-sdk/client-s3";

export function r2ForSession(creds: { accessKeyId: string; secretAccessKey: string; sessionToken: string }) {
  const config: S3ClientConfig = {
    region: "auto",
    endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
    credentials: creds,
    requestChecksumCalculation: "WHEN_REQUIRED",
  };
  return new S3Client(config);
}

Pattern C: Worker in front of the bucket (policy per request)

When every request needs a live authorization decision, put a Worker in front of the bucket with the native binding: a revoked user, a rate limit, or WAF and caching on a custom domain all need one. The full typed version is in examples/worker-gate.ts. It uses a constant-time secret compare, a deny-by-default read check, and conditional GETs.

JSON
// wrangler.jsonc  (default config format; wrangler.toml still works)
{
  "name": "media-gateway",
  "main": "src/index.ts",
  "compatibility_date": "2026-10-17",
  "r2_buckets": [
    {
      "binding": "MEDIA",          // -> env.MEDIA
      "bucket_name": "amani-media"
      // "jurisdiction": "us",     // required for jurisdictional buckets
      // "remote": true            // use the real bucket during `wrangler dev`
    }
  ]
}
Bash
npx wrangler types                  # generates Env (MEDIA: R2Bucket, ...) + runtime types
npx wrangler secret put AUTH_KEY_SECRET

Workers binding API (cheat sheet)

MethodReturnsNotes
head(key)R2Object | nullMetadata only
get(key, { onlyIf?, range?, ssecKey? })R2ObjectBody | R2Object | nullReturns an R2Object without body when onlyIf fails, so map it to 304. range takes {offset,length}, {suffix} or Headers
put(key, value, { httpMetadata?, customMetadata?, md5/sha1/sha256/sha384/sha512?, storageClass?, onlyIf?, ssecKey? })R2Object | nullnull means an onlyIf precondition failed. Writes are strongly consistent
delete(key | key[])voidUp to 1,000 keys per call
list({ prefix?, cursor?, delimiter?, limit?, include? })R2ObjectsMax 1,000 per page. Loop on truncated and cursor, never on objects.length
createMultipartUpload(key, opts?) / resumeMultipartUpload(key, uploadId)R2MultipartUploaduploadPart / complete / abort. Unfinished uploads auto-abort after 7 days

R2Object gives you key, size, etag, httpEtag (quoted: use this one in headers), uploaded, httpMetadata, customMetadata, checksums, storageClass ("Standard" | "InfrequentAccess"), and writeHttpMetadata(headers).


Choosing a pattern

NeedPatternWhy
Time-limited download of a private fileA: presigned GETNo infrastructure; the URL expires on its own
Direct browser upload, bytes skip your serverB: presigned PUT + signableHeaders + ContentLengthOffloads bandwidth; type and size are enforced by the signature
Client needs list/multipart/many ops on its own prefixT: temporary credentialsOne scoped, expiring S3 session
Live per-request authz, WAF, caching, rate limitsC: Worker (+ custom domain)Full control at the edge
Public, non-sensitive assets (logos, OG images, thumbnails)Public bucket on a custom domainOnly when leakage is harmless

Public buckets and custom domains

  • Custom domain (production): the domain must be a zone in the same Cloudflare account. A partial (CNAME) setup works. A bucket can have up to 100 custom domains. Connect it under R2 > bucket > Settings > Custom Domains, or with npx wrangler r2 bucket domain add. A custom domain unlocks Cloudflare Cache (enable Smart Tiered Cache; only default extensions are cached unless you add a Cache Everything rule), WAF custom rules, WAF token authentication (HMAC, Pro+), Cloudflare Access, Bot Management, and minimum TLS and cipher settings.
  • r2.dev (development): toggle with npx wrangler r2 bucket dev-url enable|disable. It's rate-limited and throttled, so don't CNAME a domain to it (Cloudflare doesn't support that path).
  • Disable r2.dev when you protect a custom domain with WAF or Access. Otherwise the bucket stays public through r2.dev.
  • Presigned URLs don't work on custom domains. They only work on the S3 endpoint. On a custom domain, use WAF HMAC token auth or a Worker.
  • Public buckets can't list contents at the domain root.

CORS

CORS is needed whenever a browser calls R2: a public bucket fetched cross-origin, or any presigned URL used from JS.

JSON
[
  {
    "AllowedOrigins": ["https://app.example.com", "http://localhost:3000"],
    "AllowedMethods": ["PUT", "GET", "HEAD"],
    "AllowedHeaders": ["Content-Type"],
    "ExposeHeaders": ["ETag"],
    "MaxAgeSeconds": 3600
  }
]
  • Where to set it. Paste the policy in bucket Settings > CORS Policy, send S3 PutBucketCors (examples/bucket-setup.mts), or run npx wrangler r2 bucket cors set <BUCKET> --file cors.json. Wrangler uses its own JSON shape: {"rules":[{"allowed":{"origins":[...],"methods":[...]}}]}.
  • Origins are scheme://host[:port] only: no path and no trailing slash. A pattern may contain at most one * (for example https://*.example.com). Ports can't be wildcards.
  • AllowedHeaders must list every header the browser sends on the presigned request.
  • Changes can take up to 30 s to propagate. On a custom domain, purge the cache after changing CORS, or cached responses keep the old headers.

Lifecycle rules and storage classes

Standard (default)Infrequent Access (STANDARD_IA)
Storage$0.015 / GB-month$0.01 / GB-month
Class A ops$4.50 / million$9.00 / million
Class B ops$0.36 / million$0.90 / million
Data retrievalnone$0.01 / GB
Minimum storage durationnone30 days
Free tieryesno
  • Setting a class. Per object, use PutObject({ StorageClass }) or the binding's put(..., { storageClass: "InfrequentAccess" }). A bucket can also have a default class. Change an existing object with CopyObject + x-amz-storage-class.
  • Lifecycle rules (max 1,000 per bucket) can expire objects by age or date, move them to IA after N days, and abort incomplete multipart uploads. Buckets already have a default rule that aborts multipart uploads after 7 days. Expiry usually happens within 24 h. When a delete and a transition land in the same 24 h, the delete wins. A transition costs one Class A op. Lifecycle rules can't move IA back to Standard.
  • Managing rules. Use S3 PutBucketLifecycleConfiguration, or npx wrangler r2 bucket lifecycle add|set|list|remove (--expire-days, --expire-date, --ia-transition-days).
  • Bucket locks (wrangler r2 bucket lock add|set|list|remove) set write-once retention, by age, until a date, or indefinitely. They override lifecycle deletes, and you can't empty a bucket while lock rules exist.

Event notifications

Event notifications push object-create events (PutObject, CopyObject, CompleteMultipartUpload) and object-delete events (DeleteObject, LifecycleDeletion) to a Cloudflare Queue. Read them with a consumer Worker or an HTTP pull consumer. The limits are 100 rules per bucket, with optional --prefix and --suffix filters. Rules can't overlap, and a queue takes about 5,000 messages/s.

Bash
npx wrangler queues create media-events
npx wrangler r2 bucket notification create amani-media --event-type object-create --queue media-events --prefix "uploads/"

Each message body has { account, action, bucket, object: { key, size?, eTag? }, eventTime, copySource? }. size and eTag are absent on deletes. A typical use is post-upload validation of presigned PUTs. examples/event-consumer.ts shows a typed consumer that checks the type and size, then marks the object ready or deletes it.

Jurisdictions and location hints

  • Location hints are best-effort placement: wnam, enam, weur, eeur, apac, oc. Set one in the dashboard or with S3 CreateBucket LocationConstraint. A hint is honored only the first time a bucket name is created.
  • Jurisdictions guarantee where data is stored and processed: eu, us (new 2026-08-17), and fedramp (Enterprise). You choose one at bucket creation and can never change it. Access goes only through https://<ACCOUNT_ID>.<jurisdiction>.r2.cloudflarestorage.com, so you need one S3 client per jurisdiction. Workers bindings need "jurisdiction": "<j>", and the Cloudflare API needs a cf-r2-jurisdiction header.
  • Trade-offs: Local Uploads and Data Access Logs aren't available on jurisdictional buckets. Logpush can't target them directly; use its S3-compatible endpoint instead.

Newer bucket features (2026)

  • Local Uploads (open beta from 2026-02-03; no extra cost): writes uploads to storage near the client, then replicates them to the bucket asynchronously. Cloudflare measured up to 75% lower upload time-to-last-byte. Enable with npx wrangler r2 bucket local-uploads enable <BUCKET>. Not available for jurisdictional buckets.
  • Data Access Logs (GA 2026-09-04): per-request logs of object operations (status < 400) across S3, Workers, dashboard and public access, viewed in Workers Observability. Retention is 7 days, and delivery is best-effort. Billing at Cloudflare Observability rates starts 2026-12-01. Non-jurisdictional buckets only.
  • Dashboard: empty a bucket or delete "folders" (prefixes) in one action. A new R2 Metrics page shows upload and download bandwidth, also broken down by Cloudflare location. The same data is in the GraphQL Analytics API.
  • SSE-C (customer-provided keys) works over both the S3 API and the binding (ssecKey). R2 also encrypts everything at rest by default. SSE-KMS isn't supported.

Data migration: Super Slurper and Sippy

Super SlurperSippy
ModelOne-shot bulk copy jobIncremental copy-on-read
SourcesAmazon S3, GCS, R2, any S3-compatible provider (B2, Spaces, Scaleway and Wasabi tested)Amazon S3, GCS, Azure Blob Storage and any S3-compatible provider (added 2026-07-24)
CostFree; you pay R2 Class A ops (objects ≥100 MiB use multipart)Free; you pay R2 ops (objects ≥200 MiB use multipart)
LimitsObjects > 1 TB skipped; Glacier/Deep Archive skippedSource changes after the first copy aren't re-synced
StartDashboard > R2 > Data Migrationnpx wrangler r2 bucket sippy enable <BUCKET>

The ETags of migrated objects may differ from the source, so don't verify migrations by ETag. A common pattern is Sippy to serve live traffic plus Super Slurper for the long tail.

Analytics on R2: Basin (formerly R2 Data Catalog / R2 SQL)

On 2026-10-01 Cloudflare renamed and GA'd its data platform as Basin:

  • Basin Catalog (formerly R2 Data Catalog) is a managed Apache Iceberg REST catalog built into an R2 bucket. You can query it from Spark, Snowflake, DuckDB, PyIceberg, Trino or StarRocks. Billing has run since 2026-08-03: catalog operations are $9.00/million (1M free), and compaction is $0.005/GB plus $2.00/million objects (10 GB + 1M objects free). Snapshot expiration is free. Read-only engines can use an Admin Read only token.
  • Basin SQL (formerly R2 SQL) is a serverless SQL engine over Basin Catalog tables. It costs $2.50/TB scanned (10 GB/month free, 10 MB minimum per query). EXPLAIN, SHOW and DESCRIBE are free. Run queries with npx wrangler basin sql query <warehouse> "<SQL>".
  • Basin Pipelines (formerly Cloudflare Pipelines) ingests events into Iceberg tables or files on R2.

Docs now live at developers.cloudflare.com/basin-catalog/ and /basin-sql/. The old R2 Data Catalog and R2 SQL configurations and APIs still work but are slated for future deprecation.


Pricing and limits (snapshot 2026-10-20)

Free tier (monthly, Standard only)
Storage10 GB-month
Class A ops1 million
Class B ops10 million
EgressFree (always, all classes)
  • Class A: ListBuckets, PutBucket, ListObjects, PutObject, CopyObject, CreateMultipartUpload, UploadPart(Copy), CompleteMultipartUpload, ListMultipartUploads, ListParts, PutBucketCors, PutBucketEncryption, PutBucketLifecycleConfiguration, LifecycleStorageTierTransition.
  • Class B: HeadBucket, HeadObject, GetObject, UsageSummary, GetBucketEncryption, GetBucketLocation, GetBucketCors, GetBucketLifecycleConfiguration.
  • Free: DeleteObject, DeleteBucket, AbortMultipartUpload. Unauthorized (401) requests aren't billed. Usage is rounded up to the next unit.
  • Limits: 1,000,000 buckets/account. Objects up to ~5 TiB (4.995 TiB). A single PUT or part is ~5 GiB (4.995 GiB), and multipart allows 10,000 parts. Keys are up to 1,024 bytes and metadata up to 8,192 bytes. One concurrent write per second to the same key (above that, 429). Bucket-management ops are capped at 50/s/bucket, and the Cloudflare REST API at 1,200 requests per 5 minutes. A Worker's inbound request body is also capped by Workers request limits.

Full tables are in reference/limits-and-pricing.md.


Environment Variables

Secrets (server-only; set in the vault, .env.local, or wrangler secret put):

Bash
R2_ACCESS_KEY_ID=your-r2-access-key-id
R2_SECRET_ACCESS_KEY=your-r2-secret-access-key
AUTH_KEY_SECRET=long-random-string-for-worker-writes

Non-secret configuration (plain env or Wrangler vars):

VariableExamplePurpose
R2_ACCOUNT_ID0123456789abcdef0123456789abcdefBuilds the S3 endpoint
R2_BUCKETamani-mediaPrivate media bucket name
R2_JURISDICTIONus (optional)Selects <account>.<j>.r2.cloudflarestorage.com; must match the bucket
AWS_REQUEST_CHECKSUM_CALCULATIONWHEN_REQUIRED (optional)Env alternative to the client option

codeAmani notes

  • thumbs.codeamanilabs.org is the one intentionally public bucket. The /add-tech thumbnail pipeline (packages/dashboard/scripts/generate-thumbnails.py) uploads thumbnails/<slug>.webp to a public R2 bucket served on that custom domain. That's correct for non-sensitive thumbnails. Rules for that bucket:
    • Leave r2.dev disabled: the custom domain gives you cache and WAF, and r2.dev is rate-limited.
    • Keep keys stable (slugs) with long Cache-Control, and purge the cache when a thumbnail is regenerated under the same key.
    • Manual uploads with Wrangler must pass --remote. Wrangler 4.151 defaults r2 object put/get/delete to local storage, so without the flag the object never reaches the live bucket.
    • The pipeline's Cloudflare credential stays local-only (see cloudflare/NOTES.md). Never put it in CI or an app.
  • User media is the opposite case. Receipts, ID documents and profile photos go in a private bucket behind Pattern A/B/C or T only. Namespace keys by Clerk userId and keep presigned TTLs in minutes.
  • US-first data residency. Customers are primarily in the US. When a contract or regulation requires US residency, create the bucket in the new us jurisdiction from day one, because you can't change it later. The cost is losing Local Uploads and Data Access Logs on that bucket.
  • Payments context. Stripe is the default rail, so there's no payment media to store for card flows. For Kenya-targeted projects only, M-Pesa receipts and KYC documents follow the private pattern. Short TTLs and userId-scoped keys support KDPA 2019 data-minimization.
  • Zero egress pays off for media-heavy apps. Serving images costs only operations. For Kenya-targeted, mobile-first apps on 2G/3G, direct presigned uploads (Pattern B) keep large photos off your metered app server. Local Uploads can cut upload latency for users far from the bucket region (non-jurisdictional buckets only).
  • AI routing. Cloudflare AI Search can index R2 buckets, including extensionless objects with a supported Content-Type. Keep private user media out of any bucket you index. Route generation through the normal codeAmani AI policy (Claude primary).
  • Analytics. For event or log analytics on R2, use Basin Catalog + Basin SQL rather than standing up a warehouse. Price it by data scanned ($2.50/TB).

Troubleshooting

IssueFix
Presigned PUT accepts any Content-TypeYou didn't pass signableHeaders: new Set(["content-type"]). The presigner leaves content-type unsigned by default
Presigned PUT fails (BadDigest / checksum error) or the URL has x-amz-checksum-crc32=AAAAAA==SDK ≥3.729 default checksums. Set requestChecksumCalculation: "WHEN_REQUIRED" on the presigning client
Presigned PUT returns 403 SignatureDoesNotMatchClient Content-Type (or body length, when ContentLength is signed) differs from what you signed. Send the exact same values
Browser upload blocked before reaching R2No CORS rule, or AllowedHeaders lacks Content-Type. Origins must have no path or trailing slash
Browser can't read an expired-URL errorR2 omits CORS headers on 403 ExpiredRequest. Mint fresh URLs before each upload
Presigned URL 403s on a custom domainPresigned URLs work only on <ACCOUNT_ID>.r2.cloudflarestorage.com. Use WAF HMAC token auth or a Worker on custom domains
NoSuchBucket for a bucket you can see in the dashboardIt's a jurisdictional bucket. Use <account>.<jurisdiction>.r2.cloudflarestorage.com, or "jurisdiction" on the binding
wrangler r2 object put "succeeds" but the object isn't in the bucketWrangler defaults to local storage. Add --remote
429 on writesMore than 1 write/s to the same key, or r2.dev rate limiting. Spread keys; use a custom domain
Object reachable by anyonePublic access (custom domain or r2.dev) is enabled. Disable it and serve via a presigned URL or a Worker
Worker list() loop never ends or misses objectsLoop on truncated/cursor, not on objects.length < limit
CORS changes not visible on a custom domainPurge the cache for that hostname
AccessDenied changing CORS or lifecycleObject-scoped tokens can't change bucket config. Use an Admin Read & Write token
S3 SDK fails under wrangler devThe S3 API isn't available in local wrangler dev. Use the binding ("remote": true for the real bucket)