When browsers upload large videos straight into a Cloudflare R2 bucket with presigned URLs, how are the URLs issued and what must the bucket allow?
answer
- the Worker's request body ceiling
- SigV4 signing done locally
- the account's r2.cloudflarestorage.com endpoint
- a CORS rule per origin and method
basics
~20 sA Worker signs a short-lived PUT URL for R2's S3-compatible endpoint using an R2 API token kept as a secret, and the browser uploads directly. The bucket needs a CORS rule allowing your origin, PUT and the Content-Type header.
solid answer
~50 sProxying a video through the Worker's binding runs into the request body limit of the Cloudflare plan: 100 MB on Free and Pro, 200 MB on Business, with a 413 past it. So the Worker authenticates the user, picks the key itself, and signs a URL with AWS Signature Version 4 (`aws4fetch` or the AWS SDK) against `https://<ACCOUNT_ID>.r2.cloudflarestorage.com`, region `auto`, using an R2 API token with **Object Read & Write** on that one bucket, stored with `wrangler secret put`. Signing is local, with no call to R2. Sign the `Content-Type`, keep the expiry to minutes (the ceiling is 7 days), and remember R2 supports GET, HEAD, PUT and DELETE presigned URLs but not POST policies, so check the size after upload. Presigned URLs work only on the S3 endpoint, never on a custom domain. Finally the bucket needs a CORS policy for your origin and `PUT`.
code
json · 13 lines{
"rules": [
{
"allowed": {
"origins": ["https://app.example.com"],
"methods": ["PUT", "GET", "HEAD"],
"headers": ["Content-Type"]
},
"exposeHeaders": ["ETag"],
"maxAgeSeconds": 3600
}
]
}go deeper
Know that the browser uploads to R2's S3-compatible endpoint with a URL your Worker signs, and that the bucket needs a CORS rule naming your site's origin.
Explain local SigV4 signing with an R2 API token and region auto, the 7-day expiry ceiling, and why the plan's request body limit pushes video uploads off the Worker.
Cover what the URL cannot restrict: there is no POST policy, so size is checked after upload; sign Content-Type, keep keys as secrets and expiries short.
Weigh token scope and rotation: one Object Read & Write token per bucket, who may mint URLs, and when temporary credentials should replace presigned URLs.
## Why not stream uploads through the Worker A Worker can write `request.body` straight into `env.UPLOADS.put()`, and for avatars that is the simplest design. Large videos hit a wall first: Cloudflare caps the **request body** a Worker receives according to the Cloudflare plan, and a bigger request is refused with `413 Request entity too large`. | Cloudflare plan | Maximum request body | |---|---| | Free | 100 MB | | Pro | 100 MB | | Business | 200 MB | | Enterprise | up to 5 GB, self-serve | Even under the cap, every byte would pass through the Worker. A **presigned URL** lets the browser send the bytes to R2 directly while the Worker keeps the decision about who may upload what. ## Issuing the URL A presigned URL is an ordinary R2 S3-API request whose AWS Signature Version 4 signature sits in the query string (`X-Amz-Algorithm`, `X-Amz-Credential`, `X-Amz-Date`, `X-Amz-Expires`, `X-Amz-SignedHeaders`, `X-Amz-Signature`). The flow: 1. Create an **R2 API token** with the **Object Read & Write** permission, scoped to the uploads bucket. It yields an Access Key ID and a Secret Access Key; store both with `wrangler secret put`, never as plain `vars`. 2. When the signed-in user asks to upload, the Worker chooses the key (for example `videos/<userId>/<uuid>.mp4`) instead of trusting a client-supplied name. 3. The Worker signs a `PUT` for `https://<ACCOUNT_ID>.r2.cloudflarestorage.com/<bucket>/<key>` with region `auto`, using `aws4fetch` (which runs on `fetch` and Web Crypto) or the AWS SDK. Signing happens locally; nothing is sent to R2 until the browser uses the URL. 4. The browser `PUT`s the file to that URL with the signed `Content-Type`. The Worker's checks happen before step 3, because the URL cannot be narrowed once issued: confirm the session, check the user's quota, accept only the content types you serve (`video/mp4`, `image/jpeg`), and keep each user under their own prefix. Many teams also record a pending upload in a database at this point, then mark it complete once the object appears, so an upload that never arrives can be cleaned up. ## What the URL can and cannot restrict - **Operation and object:** one method on one key. R2 accepts presigned `GET`, `HEAD`, `PUT` and `DELETE`. - **Expiry:** from 1 second to 7 days (604,800 seconds). The URL is a bearer token, reusable until it expires, so keep upload URLs to minutes. - **Content type:** a signed `Content-Type` makes any other value fail with `403 SignatureDoesNotMatch`. - **No POST policy:** R2 does not support presigned `POST` form uploads, so there is no policy document to cap the size. Check the result afterwards, for example with `head()` in a Worker, and delete what breaks your rules. - **Hostname:** presigned URLs work only on the S3 API domain, never on a custom domain connected to the bucket. - **Size:** one `PUT` stores at most 5 GiB. Longer videos need a multipart upload, either through a Worker or by a client holding **temporary credentials**, short-lived keys scoped to the bucket and to chosen operations and paths. ## The bucket's CORS policy Valid credentials do not satisfy the browser: a cross-origin `PUT` always triggers a preflight, and R2 answers it only from the bucket's **CORS policy**. - Allow your application's exact origin (`scheme://host[:port]`, no path; at most one `*` wildcard). - Allow the methods your URLs use, here `PUT`, plus `GET` and `HEAD` if the page reads objects back. - Allow every request header the client sends, at least `Content-Type`. - Expose `ETag` if the page needs it, for instance to collect part etags in a multipart upload. - `MaxAgeSeconds` caches the preflight; a policy change can, in rare cases, take up to 30 seconds to apply. The dashboard takes the S3-style array (`AllowedOrigins`, `AllowedMethods`). Wrangler 4's `wrangler r2 bucket cors set <bucket> --file cors.json` expects R2's own shape, a `rules` array with lowercase keys nested under `allowed`, and rejects the S3-style keys. ## Failure modes to expect - A URL used after expiry returns `403 ExpiredRequest` without CORS headers, so browser code sees only an opaque network error; refresh URLs before they lapse. - A client that changes `Content-Type` gets `403 SignatureDoesNotMatch`. - A missing CORS rule shows as a blocked preflight, while the same URL still works from a command-line client.
- How do you enforce a maximum upload size when R2 presigned URLs offer no POST policy?Validate after the fact. Keep expiries short, then check the written object: a `head()` in the Worker that issued the URL, or an `object-create` event notification feeding a queue consumer, reads `size` and deletes or quarantines anything over your limit. Small files can instead go through the Worker, which can check the body before calling `put()`.
- Why does an expired R2 presigned upload look like a CORS failure in the browser console?R2 answers an expired URL with `403 ExpiredRequest` but sends no CORS headers on that response, so the browser hides it from JavaScript and reports a CORS or network error. Issue URLs just before use and request a fresh one when an upload fails.
- When would you give a client R2 temporary credentials instead of a presigned URL?When it must make several S3 calls, such as a multipart upload of a video above the 5 GiB single-PUT limit. Temporary credentials are short-lived keys plus a session token, scoped to one bucket, to permitted operations and optionally to paths, and never broader than the parent token. A presigned URL covers a single operation on a single object.
- Streaming every upload through the Worker's R2 binding has no size limit
- Presigned URLs work on the custom domain connected to the bucket
- An R2 presigned POST policy can cap the size of an upload
- The R2 secret access key can live in a plain var in the Wrangler file
- A valid presigned URL needs no CORS rule for a browser upload