Back to Cloudflare

Store and Deliver Objects With R2

November 5, 2026 Updated November 6, 2026 Wasil Zafar 28 min read

Connect object APIs, private access, and browser delivery

Table of Contents

  1. Objects Have Keys and Metadata Rather Than POSIX Paths
  2. R2 APIs and S3 Compatibility Boundaries
  3. Private Objects, Signed Requests, and Public Delivery
  4. Lifecycle, Uploads, Ranges, and Cost Drivers
  5. Design an Authorized Upload and Download Flow
  6. Reject Unauthorized Requests and Validate CORS Behavior

Objects Have Keys and Metadata Rather Than POSIX Paths

There is no folder to rename. An engineer uploads avatars/u_1042/2026/11/headshot.jpg and looks for a way to rename the 2026 folder. The slashes are ordinary characters inside one string, and the bucket can only look up that string. A bucket is a flat, lexicographically ordered map from a key to an object, not a filesystem.

The vocabulary follows from that flat map. Each distinction below changes what an operation can do (Upload objects):

Term or operationMeaningOperational consequence
BucketAccount-scoped namespace plus configurationOne flat keyspace; no directory objects
KeyUTF-8 string of up to 1,024 bytesSlashes are bytes; prefix plus delimiter only simulates folders
ObjectImmutable byte sequence stored under one keyOverwrite replaces the whole body; no append or in-place edit
MetadataSystem HTTP headers plus custom x-amz-meta-* pairs, capped at 8,192 bytesReturned on a head request, not indexed or filterable
ETagOpaque validator for one uploadNot necessarily the file's MD5; a multipart ETag is derived from its parts
RenameCopyObject then DeleteObjectTwo charges and a window in which both keys exist
OverwriteLast writer winsSustained writes above roughly one per second to the same key return HTTP 429 (Limits)
ListingLexicographic and paginated; strongly consistentPrefix plus delimiter produces the folder illusion; the usual failure is pagination, not stale keys

Think of a coat check. The ticket number is the key; the coat and its claim tags are the object and its metadata. The ticket can contain slashes, but the rack is not a tree.

Key design is retention design

Lifecycle rules match prefixes, so a tenant-and-month key lets you expire one tenant or one month at a time; a key beginning with a random identifier gives you nothing to target. Metadata is a label, not a schema: R2 returns it on a head request but does not index or filter by it. For queries such as approved assets, keep the index in D1.

Objects Have Keys and Metadata Rather Than POSIX Paths
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    U["Upload avatars/u_1042/2026/11/headshot.jpg"] --> K["Key: one UTF-8 string, max 1024 bytes"]
    K --> F["Bucket: flat keyspace, lexicographic order"]
    F --> O["Object body
bytes up to 5 TiB"] F --> S["System metadata
Content-Type, Cache-Control, ETag"] F --> M["Custom metadata
x-amz-meta-*, max 8192 bytes"] F --> P["List with prefix and delimiter
avatars/u_1042/ plus /"] P --> V["Virtual folders
no inode, no atomic rename"] K --> L["Lifecycle rule
prefix avatars/, expire after 365 days"] L --> X["Deletion typically within 24 hours"] M -.->|"not indexed or queryable"| D["D1 for searchable attributes"] V -.->|"move one key"| C["CopyObject then DeleteObject"] F -.->|"two writers, same key"| W["Last writer wins
above 1 write/s returns 429"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class S primary; class U,K,F,O,M,P,V,L,X,D,C,W secondary;

Figure 1 traces the upload through the flat keyspace. The solid path is the normal write and read model; the dashed edges are filesystem assumptions that do not hold. Lifecycle attaches to the key prefix, not to a folder object, and metadata sits beside the bytes rather than inside a searchable table.

Key and object layers in an R2 bucket A request names one key. The key is a flat string, not a path. The bucket resolves it to one object envelope containing the body, system metadata, custom metadata, and an ETag. A prefix and delimiter query creates a folder-like view, while a lifecycle rule matches the prefix and expires matching objects. Request boundary PUT avatars/u_1042/ 2026/11/headshot.jpg Bucket: one flat keyspace avatars/u_1001/2026/10/a.jpg avatars/u_1042/2026/11/b.jpg logs/2026/11/05/edge.ndjson / is a byte, not a separator Object envelope Body bytes System metadata + ETag Custom metadata, max 8 KiB One key resolves to one object Folder illusion prefix + delimiter query no inode, no rename Lifecycle by prefix avatars/ expires in 365 days applies to matching keys only Boundary that surprises filesystem users Replacing an object is a whole-object write. Moving a key is CopyObject plus DeleteObject, not an atomic rename.

Figure 2 separates the boundaries that are easy to conflate: the request names a key, the bucket resolves it to one object envelope, and configuration such as lifecycle lives on the bucket rather than on a folder. The body is not addressable in pieces except through byte ranges, which later sections use for media delivery.

R2 APIs and S3 Compatibility Boundaries

The endpoint and region are the only changes. The same call that writes to S3 writes to R2 when it points at the account endpoint with region auto, because R2 implements a documented subset of the S3 API.

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

const s3 = new S3Client({
  region: "auto",
  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!,
  },
});

await s3.send(
  new PutObjectCommand({
    Bucket: "my-bucket",
    Key: "lab/hello.txt",
    Body: "hello",
  }),
);
export AWS_DEFAULT_REGION=auto
R2_ENDPOINT="https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com"

aws s3api put-object \
  --endpoint-url "$R2_ENDPOINT" \
  --bucket my-bucket \
  --key lab/hello.txt \
  --body hello.txt

Region is auto. Some tools insist on a real region; an empty value and us-east-1 alias to it.

Compatibility is an operation-by-operation matrix. A call that exists can still reject feature-level headers inside it, so test the exact combination you ship (S3 API compatibility):

Operation or surfaceWorksGap to plan around
PutObjectWrites, custom metadata, conditional writesACL, Object Lock, tagging, website redirect, and SSE-KMS headers are unsupported
CreateBucketBucket creationBucket ACLs and x-amz-expected-bucket-owner are unsupported
GetObject, HeadObject, CopyObject, DeleteObjectReads, heads, copies, deletes, range reads, conditional headers, SSE-CSame ACL and policy gaps as the write path
Multipart uploadParts, completion, abortThe ETag is derived from the parts, not from the whole file
ListObjectsV2Preferred listing with prefix and delimiterOlder ListObjects exists, but V2 is preferred
Presigned URLsGET, HEAD, PUT, and DELETEPresigned POST form uploads are unsupported (Presigned URLs)
Bucket policy, versioning, website hosting, replication, Object Lock configuration, S3 notificationsNot implementedDo not design around them
ChecksumsCRC-32, CRC-32C, SHA-1, and SHA-256 as composite; CRC-64/NVME as full-objectAn SDK's default mode can fail before the object is written
Local developmentWorkers binding under wrangler devThe S3-compatible endpoint is not available against local storage

Compatible is not portable

A successful object write says nothing about ACLs, bucket policies, versioning, or presigned form uploads. Test the exact operation and headers your application sends; the compatibility page is a per-operation matrix, not a promise that an existing S3 application runs unchanged.

SurfaceCredential and scopeOperationsChoose it whenHard boundary
Workers binding (env.BUCKET)Implicit in the Worker; no public endpointget, put, delete, list, multipart, ranges, conditional writesServer-side code already runs in a Worker and the bucket is in the same accountCannot generate presigned URLs; every caller reaches it through your Worker code
S3 APIR2 API token access key and secret, scoped to a bucket and permission groupBroad object and bucket subset from the compatibility matrixExisting S3 SDKs, CLI tools, rclone, browser uploads via presigned URLNo IAM policies, ACLs, versioning, Object Lock, website hosting, or S3 notification configuration
Cloudflare REST APICloudflare API tokenControl plane: buckets, CORS, lifecycle, custom domainsInfrastructure automation and drift checks1,200 requests per five minutes per account; not the data path
Public custom domainNone for public reads; WAF, Access, or token auth can be layered onGET and HEAD for objectsPublic assets that need cache, WAF, and bot managementNo bucket root listing; cached responses can outlive a delete or overwrite
Presigned URLSignature in the query string, derived from an R2 API tokenOne operation on one object: GET, HEAD, PUT, or DELETETime-limited browser download or direct upload without proxying bytesS3 host only, not custom domains; 1 second to 7 days; bearer token, not a session

Choose by client and failure boundary. The Workers binding is simplest when the Worker is the only client, but it cannot mint presigned URLs, so browser uploads need an S3 client. The S3 API is broadest but carries the compatibility gaps. The REST API is for configuration, not object traffic.

R2 tokens are not IAM

R2 does not use AWS IAM. An R2 API token carries a permission group and, preferably, a bucket scope; the token yields an access key ID and secret that SigV4 clients use. An AWS profile, role, or instance profile is not portable. Rotation is a token operation, not an IAM policy change. Permission changes can take up to a minute to propagate, while object operations are strongly consistent (Consistency model).

R2 APIs and S3 Compatibility Boundaries
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
    autonumber
    participant B as Browser
    participant W as Worker
    participant R as R2 S3 endpoint
    B->>W: POST /upload-url with session cookie
    W->>W: verify session, build key, sign PUT
    W-->>B: presigned URL, expires in 300 seconds
    B->>R: OPTIONS preflight with Origin and Content-Type
    alt origin is in the bucket CORS policy
        R-->>B: 204 with Access-Control-Allow-Origin
    else origin is missing or malformed
        R-->>B: response without CORS headers
        Note over B,R: Browser blocks the PUT before it is sent
    end
    B->>R: PUT signed URL with Content-Type
    alt signature valid and not expired
        R-->>B: 200 with ETag
    else expired, tampered, or header mismatch
        R-->>B: 403 ExpiredRequest or SignatureDoesNotMatch
    end
    B->>W: POST /download-url
    W-->>B: presigned GET, 60 seconds
    B->>R: GET with Range bytes=0-1023
    R-->>B: 206 Partial Content

Each failure branch has a different owner. The Worker authenticates the user and chooses the key; R2 verifies the signature and enforces expiry; the browser enforces CORS. A missing CORS header fails before the PUT leaves the browser. A signature mismatch fails at R2 and usually means a signed header such as content type changed after signing. An expired request means the URL outlived its validity window.

import { AwsClient } from "aws4fetch";

interface Env {
  R2_ACCOUNT_ID: string;
  R2_BUCKET: string;
  R2_ACCESS_KEY_ID: string;
  R2_SECRET_ACCESS_KEY: string;
}

const ALLOWED_TYPES = new Set(["image/jpeg", "image/png"]);

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    if (request.method !== "POST" || url.pathname !== "/upload-url") {
      return new Response("Not found", { status: 404 });
    }

    // Replace this header check with your real session verification.
    const userId = request.headers.get("x-user-id");
    if (!userId || !/^[a-z0-9-]{1,64}$/.test(userId)) {
      return Response.json({ error: "unauthenticated" }, { status: 401 });
    }

    const contentType = request.headers.get("content-type") ?? "";
    if (!ALLOWED_TYPES.has(contentType)) {
      return Response.json({ error: "unsupported media type" }, { status: 415 });
    }

    const extension = contentType === "image/png" ? "png" : "jpg";
    const key = `users/${userId}/${crypto.randomUUID()}.${extension}`;
    const client = new AwsClient({
      service: "s3",
      region: "auto",
      accessKeyId: env.R2_ACCESS_KEY_ID,
      secretAccessKey: env.R2_SECRET_ACCESS_KEY,
    });

    const target = new URL(
      `https://${env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com/${env.R2_BUCKET}/${key}`,
    );
    target.searchParams.set("X-Amz-Expires", "300");

    const signed = await client.sign(
      new Request(target, {
        method: "PUT",
        headers: { "Content-Type": contentType },
      }),
      { aws: { signQuery: true, allHeaders: true } },
    );

    return Response.json({ key, uploadUrl: signed.url, expiresIn: 300 });
  },
};
set -euo pipefail

: "${R2_ACCOUNT_ID:?set R2_ACCOUNT_ID}"
: "${R2_BUCKET:?set R2_BUCKET}"
: "${AWS_ACCESS_KEY_ID:?set AWS_ACCESS_KEY_ID}"
: "${AWS_SECRET_ACCESS_KEY:?set AWS_SECRET_ACCESS_KEY}"

export AWS_DEFAULT_REGION=auto
R2_ENDPOINT="https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com"

aws s3api head-bucket --endpoint-url "$R2_ENDPOINT" --bucket "$R2_BUCKET" 2>/dev/null \
  || aws s3api create-bucket --endpoint-url "$R2_ENDPOINT" --bucket "$R2_BUCKET"

head -c 12582912 /dev/urandom > fixture.bin

aws s3api put-object \
  --endpoint-url "$R2_ENDPOINT" \
  --bucket "$R2_BUCKET" \
  --key "lab/2026/11/fixture.bin" \
  --body fixture.bin \
  --content-type application/octet-stream \
  --metadata purpose=compatibility-check

aws s3api head-object \
  --endpoint-url "$R2_ENDPOINT" \
  --bucket "$R2_BUCKET" \
  --key "lab/2026/11/fixture.bin"

cat > cors.json <<'JSON'
{
  "CORSRules": [
    {
      "AllowedOrigins": ["http://localhost:8787"],
      "AllowedMethods": ["GET", "HEAD", "PUT"],
      "AllowedHeaders": ["content-type"],
      "ExposeHeaders": ["etag"],
      "MaxAgeSeconds": 3600
    }
  ]
}
JSON

aws s3api put-bucket-cors \
  --endpoint-url "$R2_ENDPOINT" \
  --bucket "$R2_BUCKET" \
  --cors-configuration file://cors.json

GET_URL=$(aws s3 presign "s3://${R2_BUCKET}/lab/2026/11/fixture.bin" \
  --endpoint-url "$R2_ENDPOINT" --expires-in 300)

curl --silent --show-error --range 0-1023 --output chunk.bin \
  --dump-header headers.txt "$GET_URL"
grep -i '^content-range' headers.txt
wc -c chunk.bin

SHORT_URL=$(aws s3 presign "s3://${R2_BUCKET}/lab/2026/11/fixture.bin" \
  --endpoint-url "$R2_ENDPOINT" --expires-in 5)
sleep 6
curl --silent --output /dev/null --write-out '%{http_code}\n' "$SHORT_URL"

The panels are two halves of one check. The TypeScript panel authenticates a caller, constrains the content type, builds a tenant-scoped key, and signs a five-minute PUT with the content type included in the signature. The bash panel creates a 12 MB fixture, writes it, reads its metadata, installs CORS, presigns a GET, requests the first 1 KB, then proves a five-second URL is rejected after six seconds. The expected status for the last command is 403.

Private Objects, Signed Requests, and Public Delivery

A new bucket is private. It has no public hostname until you enable one, and every S3 request must be signed or use a presigned URL. "Public" in R2 is a bucket-level delivery decision, not a per-object permission bit. There are three ways to get bytes to a reader, and they fail differently.

Public bucket through a custom domain. This is the production path. The domain must be a zone in the same Cloudflare account. R2 serves it through Cloudflare's cache and security layers, so you get cache rules, WAF, bot management, Access, and URL-level analytics. A bucket supports up to 100 custom domains. The bucket still does not allow listing at the root, so an object is reachable only if you know its key (Public buckets).

Public development URL. The r2.dev hostname is for testing. It is rate-limited at hundreds of requests per second, returns a 429 when exceeded, and may throttle throughput. It gives you no cache controls, WAF, or bot management. Cloudflare calls it non-production and warns against putting a CNAME in front of it (Limits).

Presigned URL or Worker proxy. These are the private paths. A presigned URL is a SigV4 signature in the query string that authorizes one operation on one object until it expires. R2 supports get, head, put, and delete on a single object, with an expiry from one second to seven days, and the URL can be reused until the deadline. Signing is server-side with no call to R2, so a Worker can mint a URL without a round trip. The URL is a bearer token: anyone holding it can perform the operation. You cannot revoke one URL before expiry; rotating the access key invalidates every URL signed with it.

A custom domain does not disable r2.dev

A team enables the development hostname for a demo and pastes object links into a shared document. Later it adds a custom domain and Access, believing the bucket is private. It is not: the development hostname is still enabled and the old links still resolve. Inventory every public surface, disable the development hostname on production buckets, and check whether a presigned URL leaked into logs; a URL in an access log is a working credential until it expires.

Ranges are how media players seek and download managers resume. A ranged GET returns partial content with a content-range header, and a head request exposes size and type without the body. A Worker using the binding can pass a range option and stream the selected bytes; a presigned URL can carry the same header. Buffering the whole object into Worker memory loses the benefit and risks the memory limit.

Lifecycle, Uploads, Ranges, and Cost Drivers

Lifecycle rules turn object storage from an ever-growing pile into a retention policy. A rule selects a prefix and either expires objects after a number of days or on a date, or transitions them from Standard to Infrequent Access. R2 has a default rule that aborts incomplete multipart uploads after seven days, and you can tighten it per prefix. Applying a deleting configuration sets x-amz-expiration on new objects immediately, but existing objects may take longer; deletion typically happens within 24 hours of the expiration value (Object lifecycles).

Three details matter. Expiration is asynchronous, so a 90-day rule does not guarantee deletion at 90 days and one second. A transition to Infrequent Access is a Class A operation, and IA has a 30-day minimum duration plus a retrieval fee, so moving small or frequently read objects can cost more than Standard. When a transition and an expiration conflict inside 24 hours, expiration wins, so design rules with unambiguous intent.

Uploads have their own boundary. A single PUT carries up to 5 GiB. Larger objects need multipart: up to 10,000 parts, each at least 5 MiB except the last, with a maximum object size of 5 TiB. The ETag of a multipart object is derived from the parts' MD5 sums and is not the MD5 of the whole file, so never compare it to a locally computed whole-file hash. Re-uploading a part number replaces the old part; if that upload fails, the original is gone. Incomplete uploads remain until the lifecycle rule aborts them.

Range reads and conditional requests make the bucket a delivery layer. A ranged read returns partial content, and a head request exposes size and metadata without the body. The standard match and date validators let a client skip an unchanged object. A write with If-None-Match: * is atomic, so among concurrent writers to an absent key at most one succeeds and the rest receive a precondition failure (S3 API compatibility).

Cost makes the architecture visible. R2 charges for storage and two operation classes, with no egress charge for any storage class. As of 2026-11-05, Standard storage is $0.015 per GB-month, Class A is $4.50 per million, and Class B is $0.36 per million. Infrequent Access is $0.01 per GB-month, $9.00 per million Class A, $0.90 per million Class B, plus $0.01 per GB retrieved. The free tier is 10 GB-month of Standard storage, one million Class A, ten million Class B, and free egress. Billing rounds up; failed authentication is not charged (Pricing).

A calculation from list prices, not a quote, makes the tradeoff legible. Twenty terabytes of Standard storage is about 20,480 GB, roughly $307 per month after the allowance. Fifty million Class B reads is about $14 after the 10 million allowance. Serving that 20 TB once adds no egress charge. A store that bills data transfer out may charge more; use current AWS rates for your region. The inversion to watch is request-dominated workloads: 500 million Class B reads is about $176 per month, which can exceed storage cost for a small, hot object set.

Lifecycle before and after Without lifecycle rules, objects remain in Standard storage indefinitely and cost grows with every retained byte. With lifecycle rules, a new object starts in Standard, transitions to Infrequent Access on day 30 with a Class A operation, and expires on day 90 with deletion typically within 24 hours. Incomplete multipart uploads abort on day 7. Without lifecycle rules Day 0 Standard Day 30 Day 90 Every byte stays billable, and the retained set grows without a bound. With lifecycle rules Day 0 Standard Day 30 IA transition Class A charge Day 90 Expire, within 24h Separate rule: incomplete multipart uploads abort on day 7.

Figure 4 contrasts the two retention postures. The upper lane is the default: Standard storage forever, with cost proportional to everything ever uploaded. The lower lane is a policy: Standard for the hot month, Infrequent Access for the warm months, expiration after the retention window, and automatic abort for uploads that never completed. The lower lane is not automatically cheaper, because the transition is a Class A operation and IA has a minimum duration and retrieval fee, but it is the only lane where retention is an explicit decision.

R2 fits immutable blobs read by key: uploads, media, backups, model artifacts, and logs. It is wrong for coordinated reads (KV), relational queries (D1), or transactional coordination (Durable Objects) (Choose a data or storage product).

Design an Authorized Upload and Download Flow

This exercise builds the flow from Figure 3 with a real bucket: authenticated upload URL, direct PUT, presigned download, CORS preflight, range read, expiry rejection, and a lifecycle rule. It is designed for a Free account and uses only controlled resources under a disposable prefix.

Guided exercise

Design an Authorized Upload and Download Flow

Status: design-only — not executed for this draft. The commands follow the documentation reviewed on 2026-11-05, but no bucket was created, no URL was signed, and no request was sent. Expected observations are documented behavior and arithmetic from list prices, not measured results.

Prerequisites and plan requirements. A Cloudflare account with R2 enabled, Node.js 20 or later, npm, AWS CLI v2, curl, and grep. No paid Workers plan is required; the R2 free tier covers this volume. You need permission to create a bucket, an R2 API token with object read and write access scoped to that bucket, and your account ID. A custom domain is not required; the exercise stays on the S3 endpoint.

Inputs. A disposable bucket name such as r2-lab-initials, the account ID, the token's access key ID and secret access key, and a 12 MB fixture generated locally. Export the four values the bash panel expects and set the region to auto.

  1. Run the bash panel from the previous section. It creates the bucket if absent, uploads a 12 MB fixture with custom metadata, prints the head response, installs CORS for the local origin, presigns a GET, and fetches the first 1 KB.
  2. Confirm the object with a head request. Expect a content length of 12,582,912 bytes, the octet-stream content type, and the custom metadata key set by the panel.
  3. Confirm the range read. Expect partial content, a content-range header that begins at byte 0 and ends at byte 1023, and exactly 1,024 bytes in the downloaded chunk.
  4. Confirm CORS. Send a preflight to the object path with the local origin, the PUT method, and the content-type request header. Expect the allowed origin echoed back. Repeat with an unlisted origin; expect no allow-origin header.
  5. Confirm expiry. The script presigns a five-second URL, waits six seconds, then prints the status. Expect 403; a 200 means the clock or expiry setting is wrong.
  6. Confirm unauthorized rejection. Request the object path without a signature; expect 403 with an access-denied code. Change one character in a valid URL's signature; expect 403 with a signature-mismatch code.
  7. Add a lifecycle rule that expires the tmp prefix after one day, upload a probe object there, and run a head request. Expect an expiration header. Do not expect deletion on a stopwatch; it is asynchronous and typically completes within 24 hours.
  8. Optionally run the TypeScript panel end to end. Replace the demo user-id header check with your real session check before treating the result as an authorization test.

Expected observations. The happy path is a 200 PUT with an ETag, a 206 range GET with 1,024 bytes, a preflight that echoes the allowed origin, and 403 for the unsigned and expired requests. A listing of the lab prefix should return the fixture and no tmp key.

Failure checks. A signature mismatch on a presigned PUT usually means the client changed the content type from the signed value. A preflight with no allow-origin header means the origin is missing, includes a path, or uses more than one wildcard. A too-small entity means a multipart part under 5 MiB was not the last part. An invalid range is a 416 and means the start offset is beyond the object size. A missing upload means the multipart upload was aborted or the ID is wrong.

Cost dimensions. A 12 MB object, a few dozen operations, and minutes of storage are inside the free tier. Beyond it, storage is $0.015 per GB-month as of 2026-11-05; requests are $4.50 per million Class A and $0.36 per million Class B. No egress charge applies. Re-check pricing before repeating at scale.

Cleanup. Delete the objects, then the bucket; R2 refuses to delete a non-empty bucket. Remove the local fixture, chunk, headers, and CORS files. Revoke the R2 API token and delete any Worker or local project.

The exercise is front-loaded with rejection tests. A flow that only demonstrates the happy path has not tested authorization; the unsigned, tampered, and expired requests are the evidence that the gate works. Step 8 is optional because the Worker adds an application-specific session layer, while steps 1 through 7 test the R2 boundary common to every implementation.

Reject Unauthorized Requests and Validate CORS Behavior

Verification date: 2026-11-05. Basis: official Cloudflare documentation reviewed on that date. Execution status: design-only; no AWS, Wrangler, curl, or Node command was run. Tested versions: none recorded.

Pass evidence. A correct implementation should produce all of the following:

  • An unsigned GET returns 403 with an access-denied code, and a tampered signature returns 403 with a signature-mismatch code.
  • A presigned URL past its expiry window returns 403; the same URL works before the deadline.
  • A preflight from an allowed origin returns an allow-origin header; a disallowed origin returns no such header.
  • A Range: bytes=0-1023 request returns 206 with a content-range header and exactly 1,024 bytes; an out-of-bounds range returns 416.
  • A create-only write with If-None-Match: * succeeds once for an absent key and returns 412 to the loser of a race.
  • A head request after a lifecycle rule shows an expiration header, while the object remains readable until asynchronous deletion.

Fail signatures. A 403 on a presigned PUT with a correct signature usually means a signed header changed. A 403 on a presigned GET from a custom domain means the URL was generated for the S3 host. A missing CORS header on an expired URL is expected, and browser JavaScript cannot read the error body. A 404 that persists after an upload on a custom domain is probably a cached 404.

Self-check. Answer before reading the explanations.

  1. Is a presigned URL a login session? No. It authorizes one operation on one object until it expires, and it is a bearer token. It cannot be revoked individually; rotating the signing key invalidates every URL signed with it.
  2. Does a CORS rule protect the bucket? No. Browsers enforce CORS; server-side clients ignore it. Bucket exposure, token scope, and signature validity are the access controls.
  3. Does a lifecycle rule delete exactly at the configured age? No. Deletion typically happens within 24 hours, with larger buckets taking longer. Do not use lifecycle as a synchronization primitive.
  4. Is "S3-compatible" a guarantee that an existing S3 application works unchanged? No. The compatibility page is an operation-level matrix with feature gaps. ACLs, bucket policies, versioning, Object Lock, website hosting, tagging, SSE-KMS, and S3 notification configuration are not implemented.

Unresolved limitations. This draft did not execute the exercise, so no latency, throughput, error rate, or bill was measured. Lifecycle timing is "typically within 24 hours," not a guaranteed deadline. Pricing and free-tier allowances are dated to 2026-11-05 and will change. The S3 compatibility matrix is a work in progress, so support can change. WAF HMAC validation requires Pro or above.

Authoritative references.

Next in the Series

In Build Relational Features With D1, we'll explore Treat schema changes and query behavior as production decisions.