Cloudflare R2 (Private Media Storage) Integration Guide
Technology: cloudflare-r2 · Category: hosting · Last reviewed: 2026-10-20
Source: https://tech-stack.codeamanilabs.org/guide/cloudflare-r2
Insight:
R2 buckets are private by default; the job is to keep them that way. Serve private media two ways: short-lived presigned URLs minted server-side, or a Worker that authorizes every request. With current AWS SDK v3 there are two traps. The presigner leaves
Content-Typeunsigned unless you passsignableHeaders. Default checksums also bake an empty-body CRC32 into presigned PUT URLs, so setrequestChecksumCalculation: "WHEN_REQUIRED". Keepr2.devfor throwaway assets: it is rate-limited and has no WAF, cache or access controls.
██████╗██╗ ██████╗ ██╗ ██╗██████╗ ███████╗██╗ █████╗ ██████╗ ███████╗ ██████╗ ██████╗
██╔════╝██║ ██╔═══██╗██║ ██║██╔══██╗██╔════╝██║ ██╔══██╗██╔══██╗██╔════╝ ██╔══██╗╚════██╗
██║ ██║ ██║ ██║██║ ██║██║ ██║█████╗ ██║ ███████║██████╔╝█████╗ ██████╔╝ █████╔╝
██║ ██║ ██║ ██║██║ ██║██║ ██║██╔══╝ ██║ ██╔══██║██╔══██╗██╔══╝ ██╔══██╗██╔═══╝
╚██████╗███████╗╚██████╔╝╚██████╔╝██████╔╝██║ ███████╗██║ ██║██║ ██║███████╗ ██║ ██║███████╗
╚═════╝╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝╚══════╝
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:
| Interface | Use it from | Auth |
|---|---|---|
S3-compatible API (https://<ACCOUNT_ID>.r2.cloudflarestorage.com) |
Next.js routes, scripts, any AWS SDK | R2 API token (Access Key ID + Secret), or temporary credentials |
Workers binding (env.MY_BUCKET.get/put/delete/list) |
Code running inside a Cloudflare Worker | The binding itself; no keys |
Public bucket (custom domain or r2.dev) |
Browsers, CDNs | None (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.
flowchart TD
A["User needs a private object"] --> B{"How much access?"}
B -->|"one operation on one object"| C["Presigned URL<br/>(SigV4, 1s to 7 days)"]
B -->|"several S3 ops in a scoped session"| T["Temporary credentials<br/>(bucket + prefix + TTL)"]
B -->|"policy decided per request"| D["Worker in front of bucket<br/>(authorize, then env.BUCKET.get)"]
C --> E["Client holds a capability URL,<br/>never your keys"]
T --> E
D --> F["Worker checks session,<br/>returns 403 or streams object"]
Versions (verified 2026-10-20)
| Package / tool | Version | Notes |
|---|---|---|
@aws-sdk/client-s3 |
3.1153.0 | Default checksum behavior changed in 3.729.0; see Checksums |
@aws-sdk/s3-request-presigner |
3.1153.0 | Keep in lockstep with client-s3 |
@cloudflare/workers-types |
5.20261019.1 | Now major 5. Cloudflare recommends npx wrangler types to generate Env + runtime types instead |
wrangler |
4.151.2 | Needs Node.js 22+ |
Official Documentation
| Resource | URL |
|---|---|
| R2 docs home | https://developers.cloudflare.com/r2/ |
| Presigned URLs | https://developers.cloudflare.com/r2/api/s3/presigned-urls/ |
| Temporary credentials | https://developers.cloudflare.com/r2/api/s3/temporary-credentials/ |
| S3 API compatibility | https://developers.cloudflare.com/r2/api/s3/api/ |
| Workers API reference | https://developers.cloudflare.com/r2/api/workers/workers-api-reference/ |
| Public buckets / custom domains | https://developers.cloudflare.com/r2/buckets/public-buckets/ |
| CORS | https://developers.cloudflare.com/r2/buckets/cors/ |
| Event notifications | https://developers.cloudflare.com/r2/buckets/event-notifications/ |
| Data location and jurisdictions | https://developers.cloudflare.com/r2/reference/data-location/ |
| Pricing | https://developers.cloudflare.com/r2/pricing/ |
| Limits | https://developers.cloudflare.com/r2/platform/limits/ |
| API tokens | https://developers.cloudflare.com/r2/api/tokens/ |
The privacy model (read this first)
flowchart LR
P["Private bucket<br/>(default)"] -->|"NEVER for sensitive media"| Pub["Public: custom domain or r2.dev"]
P -->|"recommended"| Pre["Presigned URLs<br/>short TTL"]
P -->|"recommended"| Wk["Worker gate<br/>auth per request"]
Pub -->|"only safe with"| WAF["custom domain +<br/>WAF token auth / Access"]
Six rules that keep media private:
- 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.
- 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_*. - 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.
- Actually sign what you validate. Pass
signableHeaders: new Set(["content-type"])togetSignedUrl. Without it, the presigner leavesContent-Typeout of the signature (see Pattern B). r2.devis for development only. It's rate-limited (hundreds of requests per second, then429) and has no WAF, cache, Access or Bot Management. Production goes behind a custom domain or a Worker.- 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:
| Permission | Allows |
|---|---|
| Admin Read & Write | Create, list and delete buckets; edit bucket config (CORS, lifecycle, locks); read and write objects; read and write Basin Catalog |
| Admin Read only | List buckets, view config, read and list objects, read Basin Catalog |
| Object Read & Write | Read, write and list objects in specific buckets (S3 API only) |
| Object Read only | Read and list objects in specific buckets (S3 API only) |
npm install @aws-sdk/client-s3@3.1153.0 @aws-sdk/s3-request-presigner@3.1153.0
// 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/UploadPartcalls 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 withBadDigest(400, error code 10037). - Presigned PUT URLs (verified on 3.1153.0) get
x-amz-checksum-crc32=AAAAAA==andx-amz-sdk-checksum-algorithm=CRC32baked 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.
// 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-presigneraddscontent-typeto its unsignable headers by default. Without this option,X-Amz-SignedHeadersis justhost, and the client can PUT any type under your key.ContentLength. WithsignableHeadersset, 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.
// 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 });
}
// 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
PUTfrom your origin withAllowedHeaders: ["Content-Type"](see CORS). R2 sends no CORS headers on a403 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 presignedGET,HEAD,PUTandDELETE.
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,secretAccessKeyandsessionTokento the SDK. The session token travels inX-Amz-Security-Token. - Revoke them by revoking the parent token. A credential can't exceed its parent's permissions.
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.
// 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`
}
]
}
npx wrangler types # generates Env (MEDIA: R2Bucket, ...) + runtime types
npx wrangler secret put AUTH_KEY_SECRET
Workers binding API (cheat sheet)
| Method | Returns | Notes |
|---|---|---|
head(key) |
R2Object | null |
Metadata only |
get(key, { onlyIf?, range?, ssecKey? }) |
R2ObjectBody | R2Object | null |
Returns 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 | null |
null means an onlyIf precondition failed. Writes are strongly consistent |
delete(key | key[]) |
void |
Up to 1,000 keys per call |
list({ prefix?, cursor?, delimiter?, limit?, include? }) |
R2Objects |
Max 1,000 per page. Loop on truncated and cursor, never on objects.length |
createMultipartUpload(key, opts?) / resumeMultipartUpload(key, uploadId) |
R2MultipartUpload |
uploadPart / 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
| Need | Pattern | Why |
|---|---|---|
| Time-limited download of a private file | A: presigned GET | No infrastructure; the URL expires on its own |
| Direct browser upload, bytes skip your server | B: presigned PUT + signableHeaders + ContentLength |
Offloads bandwidth; type and size are enforced by the signature |
| Client needs list/multipart/many ops on its own prefix | T: temporary credentials | One scoped, expiring S3 session |
| Live per-request authz, WAF, caching, rate limits | C: Worker (+ custom domain) | Full control at the edge |
| Public, non-sensitive assets (logos, OG images, thumbnails) | Public bucket on a custom domain | Only 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 withnpx 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.devwhen you protect a custom domain with WAF or Access. Otherwise the bucket stays public throughr2.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.
[
{
"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 runnpx 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 examplehttps://*.example.com). Ports can't be wildcards. AllowedHeadersmust 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 retrieval | none | $0.01 / GB |
| Minimum storage duration | none | 30 days |
| Free tier | yes | no |
- Setting a class. Per object, use
PutObject({ StorageClass })or the binding'sput(..., { storageClass: "InfrequentAccess" }). A bucket can also have a default class. Change an existing object withCopyObject+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, ornpx 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.
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 S3CreateBucketLocationConstraint. 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), andfedramp(Enterprise). You choose one at bucket creation and can never change it. Access goes only throughhttps://<ACCOUNT_ID>.<jurisdiction>.r2.cloudflarestorage.com, so you need one S3 client per jurisdiction. Workers bindings need"jurisdiction": "<j>", and the Cloudflare API needs acf-r2-jurisdictionheader. - 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 Slurper | Sippy | |
|---|---|---|
| Model | One-shot bulk copy job | Incremental copy-on-read |
| Sources | Amazon 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) |
| Cost | Free; you pay R2 Class A ops (objects ≥100 MiB use multipart) | Free; you pay R2 ops (objects ≥200 MiB use multipart) |
| Limits | Objects > 1 TB skipped; Glacier/Deep Archive skipped | Source changes after the first copy aren't re-synced |
| Start | Dashboard > R2 > Data Migration | npx 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,SHOWandDESCRIBEare free. Run queries withnpx 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) | |
|---|---|
| Storage | 10 GB-month |
| Class A ops | 1 million |
| Class B ops | 10 million |
| Egress | Free (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):
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):
| Variable | Example | Purpose |
|---|---|---|
R2_ACCOUNT_ID |
0123456789abcdef0123456789abcdef |
Builds the S3 endpoint |
R2_BUCKET |
amani-media |
Private media bucket name |
R2_JURISDICTION |
us (optional) |
Selects <account>.<j>.r2.cloudflarestorage.com; must match the bucket |
AWS_REQUEST_CHECKSUM_CALCULATION |
WHEN_REQUIRED (optional) |
Env alternative to the client option |
codeAmani notes
thumbs.codeamanilabs.orgis the one intentionally public bucket. The/add-techthumbnail pipeline (packages/dashboard/scripts/generate-thumbnails.py) uploadsthumbnails/<slug>.webpto a public R2 bucket served on that custom domain. That's correct for non-sensitive thumbnails. Rules for that bucket:- Leave
r2.devdisabled: the custom domain gives you cache and WAF, andr2.devis 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 defaultsr2 object put/get/deleteto 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.
- Leave
- 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
userIdand 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
usjurisdiction 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
| Issue | Fix |
|---|---|
Presigned PUT accepts any Content-Type |
You 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 SignatureDoesNotMatch |
Client Content-Type (or body length, when ContentLength is signed) differs from what you signed. Send the exact same values |
| Browser upload blocked before reaching R2 | No CORS rule, or AllowedHeaders lacks Content-Type. Origins must have no path or trailing slash |
| Browser can't read an expired-URL error | R2 omits CORS headers on 403 ExpiredRequest. Mint fresh URLs before each upload |
| Presigned URL 403s on a custom domain | Presigned 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 dashboard |
It'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 bucket |
Wrangler defaults to local storage. Add --remote |
429 on writes |
More than 1 write/s to the same key, or r2.dev rate limiting. Spread keys; use a custom domain |
| Object reachable by anyone | Public 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 objects |
Loop on truncated/cursor, not on objects.length < limit |
| CORS changes not visible on a custom domain | Purge the cache for that hostname |
AccessDenied changing CORS or lifecycle |
Object-scoped tokens can't change bucket config. Use an Admin Read & Write token |
S3 SDK fails under wrangler dev |
The S3 API isn't available in local wrangler dev. Use the binding ("remote": true for the real bucket) |
Official docs:
- https://developers.cloudflare.com/r2/
- https://developers.cloudflare.com/r2/api/s3/presigned-urls/
- https://developers.cloudflare.com/r2/api/s3/temporary-credentials/
- https://developers.cloudflare.com/r2/api/workers/workers-api-reference/
- https://developers.cloudflare.com/r2/buckets/public-buckets/
- https://developers.cloudflare.com/r2/buckets/cors/
- https://developers.cloudflare.com/r2/buckets/event-notifications/
- https://developers.cloudflare.com/r2/reference/data-location/
- https://developers.cloudflare.com/r2/pricing/
- https://developers.cloudflare.com/r2/api/tokens/