Skip to main content

r2

@rtorcato/cf-common/r2 wraps an R2Bucket binding. Raw object calls pass straight through, and the *JSON helpers cover the common case of storing a small JSON document.

import { createR2Store, multipartUpload } from '@rtorcato/cf-common/r2'
import { getBinding } from '@rtorcato/cf-common/env'
import { CloudflareError } from '@rtorcato/cf-common/errors'

interface Manifest {
name: string
size: number
}

const files = createR2Store<Manifest>(getBinding<R2Bucket>(env, 'UPLOADS'))

Files​

// stream a request body straight in
await files.put(key, request.body, {
httpMetadata: { contentType: request.headers.get('content-type') ?? undefined },
})

// serve it back, replaying only content types you trust
const SAFE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
const object = await files.get(key) // R2ObjectBody | null
if (!object) throw new CloudflareError('Not found', { status: 404 })
const stored = object.httpMetadata?.contentType ?? ''
return new Response(object.body, {
headers: {
'content-type': SAFE_TYPES.has(stored) ? stored : 'application/octet-stream',
'x-content-type-options': 'nosniff',
},
})

The stored content-type is whatever the uploader sent. Served back unchecked, it lets anyone who can upload store text/html or image/svg+xml and run script on your Worker's origin. Check it against an allowlist, send nosniff, and keep uploads behind auth as the R2 uploads example does.

head(key) returns the metadata without the body, and delete takes a key or an array of keys.

JSON documents​

await files.putJSON(`${key}.json`, { name: 'report.pdf', size: 52_013 })
const manifest = await files.getJSON(`${key}.json`) // Manifest | null

putJSON sets content-type: application/json for you. If you pass your own httpMetadata, it replaces that default. getJSON returns null for a missing key and throws R2_PARSE_FAILED when the object isn't valid JSON.

Listing​

const { objects, truncated, cursor } = await files.list({ prefix: 'reports/', limit: 100 })

list passes through to the binding, so paginate with cursor while truncated is true.

Large uploads​

multipartUpload runs a whole multipart upload: it creates the upload, sends every part, and completes it. If any part fails, it aborts the upload and throws R2_MULTIPART_FAILED, so no half-finished upload is left behind.

const object = await multipartUpload(bucket, 'videos/intro.mp4', [part1, part2, part3], {
httpMetadata: { contentType: 'video/mp4' },
})

You split the parts yourself. Every part except the last must be at least 5 MiB, which is R2's limit. Parts upload in parallel.

Presigned URLs​

The binding can't sign URLs. presignR2Url from @rtorcato/cf-common/r2-presign does it over R2's S3-compatible API with an R2 API token, so a client can upload or download one object directly:

import { requireEnv } from '@rtorcato/cf-common/env'
import { presignR2Url } from '@rtorcato/cf-common/r2-presign'

const url = await presignR2Url({
accountId: requireEnv(env, 'R2_ACCOUNT_ID'),
accessKeyId: requireEnv(env, 'R2_ACCESS_KEY_ID'),
secretAccessKey: requireEnv(env, 'R2_SECRET_ACCESS_KEY'),
bucket: 'uploads',
key: `avatars/${userId}.png`,
method: 'PUT',
expiresIn: 300,
})

See the presigned URLs example for setup.

For a full walkthrough, see the R2 uploads example. See the r2 API reference for every option.