When the object isn’t meant for the open web — a paid download, a private user upload, a generated report — a public R2 custom domain is the wrong tool. The right one is a Worker that sits between the caller and R2, checks authorization, and either streams the object back or issues a time-limited URL the browser can hit directly. This article walks the two patterns side by side: signed URLs generated and verified by your Worker (HMAC), and S3-style presigned URLs that point at the R2 S3 endpoint. They solve overlapping problems with different trade-offs around caching, traffic path, and the surface you expose to the public internet.
How to verify
Two ways to confirm you have a Worker-in-front-of-R2 path working. First, check the binding is wired in wrangler.toml and the script can resolve it.
# Confirm the Worker has an R2 binding
cat wrangler.toml | grep -A 3 "\[\[r2_buckets\]\]"
# Tail the production logs in real time
npx wrangler tail my-r2-worker --format pretty
# Hit a signed URL — should return 200 and the object body
curl -sS -D - "https://files.example.com/report-2026-q1.pdf?sig=<hex>&exp=1717372800" | head -20
# Hit it again past the expiry — should be 403
curl -sS -D - "https://files.example.com/report-2026-q1.pdf?sig=<hex>&exp=1700000000" | head -5
# Check Worker CPU + request stats
npx wrangler deployments list my-r2-worker
If the binding is present in wrangler.toml and the script references env.MY_R2, the Worker can call env.MY_R2.get(key) to fetch any object in the bound bucket. The hard part isn’t the binding; it’s the signing logic.
What’s happening
Two distinct mechanisms for time-limited access to R2 objects, and they are easy to confuse.
HMAC signature inside a Worker. Your Worker generates a URL like https://files.example.com/<key>?exp=<unix>&sig=<hex>. The signature is HMAC-SHA256 over the key and the expiry, using a secret stored in the Worker’s environment. The caller fetches that URL; a Worker route picks it up, recomputes the HMAC, compares (constant-time), checks expiry, and either streams the object from R2 or returns 403. The object never leaves R2 except through the Worker. You control everything: headers, range support, byte rewriting, response codes.
S3 presigned URLs. Your code (anywhere — Worker, server, CLI) uses the R2 access key and Signature V4 to generate a URL pointing at <account-id>.r2.cloudflarestorage.com/<bucket>/<key>?X-Amz-Expires=3600&X-Amz-Signature=.... The caller fetches that URL directly, bypassing the Worker. R2 verifies the signature itself. Useful when you have a server-side process that needs to hand a client a short-lived upload or download URL without proxying the bytes.
Why prefer the Worker path. Cache reuse: once the Worker has streamed an object from R2 with a Cache-Control header, Cloudflare’s CDN can serve the next caller without re-touching R2 — for popular objects that means one class-B read per cache lifetime instead of one per request. Header control: you can rewrite Content-Disposition per request (force attachment; filename="invoice-2026-q1.pdf") without ever changing the stored object. Streaming: R2ObjectBody.body is a ReadableStream you can pipe directly into the Response, so even 10 GB files don’t blow the Worker’s memory budget. Range support: pass through Range headers for video scrubbing without any extra code.
Why prefer the S3 presigned path. The Worker isn’t in the upload path — a browser can PUT directly to R2 against a presigned URL, bypassing both your Worker’s request limits and the Worker CPU cost. For large uploads (multi-GB) or upload-heavy workflows (image hosting, video CMS), this matters. The presigned URL is also the right answer when the consumer is a third-party tool that already speaks S3 V4 (Plex, OBS, FFmpeg’s -i s3://, …).
A practical rule: signed reads with HMAC through a Worker; presigned writes for direct-to-R2 uploads.
The procedure
1. Wire the R2 binding in wrangler.toml. The binding name (MY_R2 here) is what your code references via env.MY_R2. For development, point preview_bucket_name at a separate bucket so test traffic doesn’t touch prod.
name = "files-worker"
main = "src/worker.ts"
compatibility_date = "2026-05-01"
route = { pattern = "files.example.com/*", custom_domain = true }
[[r2_buckets]]
binding = "MY_R2"
bucket_name = "files-prod"
preview_bucket_name = "files-dev"
[vars]
SIGNED_URL_EXPIRY_SECONDS = "900"
Store the HMAC secret out-of-band:
npx wrangler secret put SIGNING_KEY
# paste a 32-byte base64 string when prompted
2. Sign URLs inside the Worker. This is the function that issues the URL after you’ve checked authentication (cookie, JWT, whatever your app uses).
async function signUrl(key: string, ttlSeconds: number, secret: string): Promise<string> {
const expiry = Math.floor(Date.now() / 1000) + ttlSeconds;
const payload = `${key}:${expiry}`;
const keyBuf = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
);
const sig = await crypto.subtle.sign('HMAC', keyBuf, new TextEncoder().encode(payload));
const sigHex = [...new Uint8Array(sig)].map(b => b.toString(16).padStart(2, '0')).join('');
return `https://files.example.com/${encodeURIComponent(key)}?exp=${expiry}&sig=${sigHex}`;
}
3. Verify and stream in the Worker fetch handler. The same HMAC, computed on the request, compared in constant time.
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
const key = decodeURIComponent(url.pathname.slice(1));
const exp = parseInt(url.searchParams.get('exp') ?? '0', 10);
const sigHex = url.searchParams.get('sig') ?? '';
if (!key || !exp || !sigHex) return new Response('bad request', { status: 400 });
if (Math.floor(Date.now() / 1000) > exp) return new Response('expired', { status: 403 });
const payload = `${key}:${exp}`;
const keyBuf = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(env.SIGNING_KEY),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
);
const expected = await crypto.subtle.sign('HMAC', keyBuf, new TextEncoder().encode(payload));
const expectedHex = [...new Uint8Array(expected)].map(b => b.toString(16).padStart(2, '0')).join('');
// Constant-time compare
if (expectedHex.length !== sigHex.length) return new Response('bad sig', { status: 403 });
let diff = 0;
for (let i = 0; i < expectedHex.length; i++) {
diff |= expectedHex.charCodeAt(i) ^ sigHex.charCodeAt(i);
}
if (diff !== 0) return new Response('bad sig', { status: 403 });
// Fetch from R2 with Range passthrough
const range = request.headers.get('Range');
const obj = range
? await env.MY_R2.get(key, { range: rangeFromHeader(range) })
: await env.MY_R2.get(key);
if (!obj) return new Response('not found', { status: 404 });
const headers = new Headers();
obj.writeHttpMetadata(headers);
headers.set('etag', obj.httpEtag);
headers.set('cache-control', 'private, max-age=300');
headers.set('content-disposition', `attachment; filename="${key.split('/').pop()}"`);
return new Response(obj.body, { status: range ? 206 : 200, headers });
},
};
The obj.body is a ReadableStream. The response streams to the client without the Worker buffering the file in memory — works for files of any practical size. obj.writeHttpMetadata(headers) copies the stored object’s content-type and any user metadata onto the response.
4. For uploads, generate an S3 presigned URL instead. Browser hits your Worker for the URL, then uploads directly to R2. Use the AWS SDK v3 inside a Worker (it works on Workers’ fetch runtime) or any V4 signing library:
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
async function presignedUpload(key: string, env: Env): Promise<string> {
const s3 = new S3Client({
region: 'auto',
endpoint: `https://${env.ACCOUNT_ID}.r2.cloudflarestorage.com`,
credentials: {
accessKeyId: env.R2_ACCESS_KEY,
secretAccessKey: env.R2_SECRET_KEY,
},
});
return getSignedUrl(s3, new PutObjectCommand({
Bucket: env.R2_BUCKET,
Key: key,
ContentType: 'application/octet-stream',
}), { expiresIn: 600 });
}
The client then issues PUT <presigned-url> with the file body. R2 verifies the signature, accepts the upload, and your Worker never touches the bytes.
5. Cache the response for popular objects. A Cache-Control header on the Worker’s response makes the CDN cache the response — including the signed URL as the cache key. That can be the right behavior if the signed URL is reused across multiple callers (e.g. a download link emailed to a customer), or the wrong behavior if every caller gets a fresh signature. Strip the sig and exp query params from the cache key with the Custom Cache Keys feature so the same object caches once across all signatures.
Common pitfalls
- Using string equality on the HMAC instead of constant-time compare — opens a timing oracle that lets an attacker extract bytes of the signature.
- Embedding the signing key in the Worker source instead of using
wrangler secret, then committing the key to git. - Forgetting to pass
Rangethrough toenv.MY_R2.get()— video scrubbing and partial downloads break with a 200 that returns the whole file. - Caching the Worker response with the default cache key, which includes
sigandexp— every signature gets its own cache entry and you re-fetch R2 on every signed URL. - Generating S3 presigned URLs with a TTL of hours when minutes would do — a leaked URL is valid for the whole window.
In the engagements we run, the Worker-in-front-of-R2 pattern is what turns object storage into something usable for private-content workflows. The shape of the Worker rarely changes; what changes is the authorization logic that decides who gets a signed URL. Managed Operations is where we run that code and its access policies for clients.