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-Type unsigned unless you pass signableHeaders. Default checksums also bake an empty-body CRC32 into presigned PUT URLs, so set requestChecksumCalculation: "WHEN_REQUIRED". Keep r2.dev for 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:

  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:

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:

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:

// 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 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.

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

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
  }
]

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

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

Newer bucket features (2026)

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:

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)

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


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: