Skip to main content

@rtorcato/cf-common

Interfaces​

R2PresignOptions​

Defined in: index.ts:8

Options for presignR2Url.

Properties​

accountId​

accountId: string

Defined in: index.ts:10

Your Cloudflare account id (32 hex characters).

accessKeyId​

accessKeyId: string

Defined in: index.ts:12

An R2 API token's access key id.

secretAccessKey​

secretAccessKey: string

Defined in: index.ts:14

An R2 API token's secret access key. Keep it in a secret, never a var.

bucket​

bucket: string

Defined in: index.ts:16

The bucket name. Empty, . and .. are rejected.

key​

key: string

Defined in: index.ts:18

The object key. / separates path segments; . and .. segments are rejected.

method?​

optional method?: "GET" | "PUT"

Defined in: index.ts:20

GET to download, PUT to upload. Defaults to GET.

expiresIn?​

optional expiresIn?: number

Defined in: index.ts:22

Seconds the URL stays valid, from 1 to 604800 (7 days). Defaults to 3600.

date?​

optional date?: Date

Defined in: index.ts:24

The signing time. Defaults to now.

Functions​

presignR2Url()​

presignR2Url(options): Promise<string>

Defined in: index.ts:51

Sign a presigned GET or PUT URL for an R2 object, over R2's S3-compatible endpoint (<accountId>.r2.cloudflarestorage.com). Anyone holding the URL can download or upload that one object until it expires, with no other credentials.

R2 bindings can't do this: it needs an R2 API token's access key and secret, and AWS SigV4 signing, done here with Web Crypto (no dependency).

Only the host header is signed, so a PUT client may send any Content-Type. Throws a non-exposed 500 R2_PRESIGN_INVALID for a bad accountId, bucket (empty, . or ..) or expiresIn, and an exposed 400 R2_PRESIGN_INVALID_KEY for an empty key or one with a . or .. segment, since keys often come from users.

Example​

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,
})

Parameters​

options​

R2PresignOptions

Returns​

Promise<string>