Cloudflare R2 uploads: bucket keys, CORS and presigned URLs

Set up Cloudflare R2 for file uploads: a private bucket, S3 keys scoped to it, endpoint and region values, presigned URLs, and the CORS policy.

Simon, Founder of Shipyard

By · Founder of Shipyard

6 minute read

Five values make any S3 library work with R2

Cloudflare R2 is object storage that speaks the Amazon S3 protocol, so setting it up for uploads comes down to creating a bucket, creating keys that can touch only that bucket, and giving your S3 client five values. If browsers upload directly, you also add a CORS policy to the bucket. Nothing else is required for a first working upload.

VariableValueNotes
S3_ENDPOINThttps://<ACCOUNT_ID>.r2.cloudflarestorage.comNo bucket name in it. Buckets created in a jurisdiction use a different host, for example <ACCOUNT_ID>.eu.r2.cloudflarestorage.com
S3_REGIONautoAn empty value and us-east-1 are accepted as aliases, for tools that insist on a real AWS region
S3_BUCKETThe bucket name3 to 63 characters: lowercase letters, digits and hyphens, not starting or ending with a hyphen
S3_ACCESS_KEY_IDThe ID half of the key pairAn identifier, not a secret
S3_SECRET_ACCESS_KEYThe secret halfShown once when the token is created

Bucket first

R2 has to be switched on for the account before anything else works. That is a one-time step in the dashboard under R2 Object Storage and it asks for a payment method, even if you never leave the free allowance. Until it is done, neither the dashboard nor the API will create a bucket or an R2 token.

After that a bucket is one command, or one form in the dashboard. A new bucket is private: no object in it can be fetched without credentials. Leave it that way for user uploads.

npx wrangler r2 bucket create myapp-uploads

Keys that open one bucket only

An account-wide key in one app means a bug in that app can read the files of every other product you run. R2 lets you avoid that.

  1. In the Cloudflare dashboard open R2 Object Storage, then Overview.
  2. Under Account Details, press Manage next to API Tokens.
  3. Choose Create Account API token. An account token survives if your personal user is removed from the account; a user token inherits your own permissions and dies with your membership.
  4. Pick the permission Object Read & Write.
  5. Scope the token to the one bucket.
  6. Create it and copy the Access Key ID and the Secret Access Key. The secret cannot be viewed again.

Where the key pair really comes from

The dashboard hides a detail that matters if you automate this. An R2 key pair is an ordinary Cloudflare API token wearing S3 clothes. The Access Key ID is the token's id. The Secret Access Key is the SHA-256 hash of the token's value. So a script that may create Cloudflare API tokens can mint bucket-scoped S3 credentials with no dashboard visit: create a token whose policy names one bucket and the permission group Workers R2 Storage Bucket Item Write, then derive the pair from the response. The body of that request closes this section.

The resource string follows a fixed pattern of account ID, jurisdiction and bucket name. For a bucket created without a jurisdiction the middle part is the word default.

One consequence follows from this design. Tokens with the two Object permissions are understood only by the S3-compatible API. Point one at Cloudflare's REST API on api.cloudflare.com and a bucket-scoped token is rejected with a 403 and the body {"code":10000,"message":"Authentication error"}. The token is fine. It is being shown to the wrong API.

JSON
{
  "name": "myapp-uploads-keys",
  "policies": [
    {
      "effect": "allow",
      "resources": {
        "com.cloudflare.edge.r2.bucket.<ACCOUNT_ID>_default_myapp-uploads": "*"
      },
      "permission_groups": [
        { "id": "<id of 'Workers R2 Storage Bucket Item Write'>" }
      ]
    }
  ]
}

Client configuration

With the AWS SDK for JavaScript the client needs the endpoint, the region and the pair. The SDK refuses to run without a region, which is the only reason auto is there.

TypeScript
import { S3Client } from '@aws-sdk/client-s3'

export const s3 = new S3Client({
  region: process.env.S3_REGION,        // "auto"
  endpoint: process.env.S3_ENDPOINT,    // https://<ACCOUNT_ID>.r2.cloudflarestorage.com
  credentials: {
    accessKeyId: process.env.S3_ACCESS_KEY_ID!,
    secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,
  },
})

Browser uploads: a presigned URL and a CORS policy

Sending a large file through your own server wastes its memory and its request time limit. The usual pattern is a presigned URL: your server signs a short-lived link for one operation on one object, and the browser sends the file straight to R2 with a PUT. Signing is pure computation on your server with no call to Cloudflare. Expiry can be anything from one second to seven days.

Four facts about R2's presigned URLs save an afternoon each. A CORS policy that allows uploads from one site and from local development follows the list.

JSON
[
  {
    "AllowedOrigins": ["https://myapp.com", "http://localhost:3000"],
    "AllowedMethods": ["PUT", "GET"],
    "AllowedHeaders": ["Content-Type"],
    "ExposeHeaders": ["ETag"],
    "MaxAgeSeconds": 3600
  }
]

Reading the errors

Paste the policy above under the bucket's Settings, CORS Policy, Add CORS policy, on the JSON tab. Then, when something still fails, find the row that matches what you see.

SymptomCauseFix
Browser console shows a CORS error, with a 401 or 403 listed above itNot CORS. The request was refused and the refusal carried no CORS headersFix the credentials or signature first. Repeating the request with curl gives a readable error body
CORS error on upload with no 401 or 403The policy lacks your origin, the PUT method, or a header the browser sends such as Content-TypeAdd the missing entry. Origins must match scheme and port exactly
403 SignatureDoesNotMatchA signed header differs from what was sent, or the URL was edited after signingSend the same Content-Type that was signed. Never alter the query string
403 ExpiredRequest, unreadable from JavaScriptThe presigned URL expired. R2 sends no CORS headers on that response, so the browser hides the bodyRequest a fresh URL shortly before uploading, not when the page loads
Bucket creation refused with a message about enabling or purchasing R2R2 was never switched on for the accountEnable it once in the dashboard
403 Authentication error, code 10000An object-level token used against the REST APIUse the S3 endpoint

Files that everyone may read

Avatars and images in public pages do not need signed links. Connect a custom domain to the bucket under its settings and Cloudflare serves the objects through its cache, with the usual controls available in front. The dashboard also offers a public development URL on r2.dev. Cloudflare documents it as rate limited and meant for development only, and it advises against pointing a CNAME of your own at it. If you later put access rules on the custom domain, disable the r2.dev URL, or the bucket stays readable through that side door.

What it costs to start

As of November 2026 Cloudflare's pricing page lists a monthly free tier for standard storage of 10 GB stored, 1 million Class A operations (writes and lists) and 10 million Class B operations (reads). Data transfer out to the internet is free at any volume. Beyond the free tier you pay for storage and operations. Read the current figures on Cloudflare's pricing page before you plan around them.

Shipyard's share of this

With R2 chosen as file storage, Shipyard creates a bucket named after the project and then mints the key pair exactly as described above: it looks up the Workers R2 Storage Bucket Item Write permission group, creates a token named shipyard-r2-<bucket> whose policy names that one bucket, and derives the two S3 values from the response. It writes all five variables from the table to your host. The secret goes through the keychain on your computer; the other four are not secrets.

Minting needs the permission Account: API Tokens: Edit on the Cloudflare token you gave Shipyard. That is a broad permission, and if you leave it out the bucket is still created and Shipyard tells you to create an Object Read & Write token by hand and add the two key variables yourself. It will not switch R2 on for your account, it does not add a CORS policy or a custom domain, and on teardown it refuses to delete a bucket that still contains files.

Sources

Launch in an hour, not a weekend

Shipyard connects your accounts once, then sets up the domain, hosting, database, email and payments for every new product.

See how it works

Read next