R2
The in-Worker R2 API is accessed by binding an R2 bucket to a Worker . The Worker you write can expose external access to buckets via a route, or manipulate R2 objects internally.
The R2 API includes some extensions and semantic differences from the S3 API. If you need S3 compatibility, consider using the S3 compatible API .
Concepts
R2 organizes the data you store, called objects, into containers, called buckets. Buckets are the fundamental unit of performance scaling and access within R2.
Creating a binding
To bind your R2 bucket to your Worker, add the following to your wrangler.toml
file. Update the binding
property to a valid JavaScript variable identifier and bucket_name
to the name of your R2 bucket:
[[r2_buckets]]
binding = 'MY_BUCKET' # <~ valid JavaScript variable name
bucket_name = '<YOUR_BUCKET_NAME>'
Within your Worker, your bucket binding is now available under the MY_BUCKET
variable and you can begin interacting with it using the bucket methods described below.
Bucket method definitions
The following methods are available on the bucket binding Object injected into your code.
For example, to issue a PUT object request using the binding above:
addEventListener("fetch", (event) => { event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) { const url = new URL(request.url); const key = url.pathname.slice(1);
switch (request.method) { case "PUT": await MY_BUCKET.put(key, request.body); return new Response(`Put ${key} successfully!`);
}
head(keystring, optionsR2HeadOptions )
Promise<R2Object|null>
- Retrieves the R2Object for the given key containing only object metadata, if the key exists, and null if the key does not exist.
get(keystring, optionsR2GetOptions )
Promise<R2Object|null>
- Retrieves the R2Object for the given key containing object metadata and the object body as a
ReadableStream
, if the key exists, and null if the key does not exist. - In the event that a precondition specified in
options
fails,get()
returns anR2Object
withbody
undefined.
- Retrieves the R2Object for the given key containing object metadata and the object body as a
put(keystring, valueReadableStream|ArrayBuffer|ArrayBufferView|string|null|Blob, optionsR2PutOptions )
Promise<R2Object>
- Stores the given
value
and metadata under the associatedkey
. Once the write succeeds, returns an R2Object containing metadata about the stored Object. - R2 writes are strongly consistent. Once the Promise resolves, all subsequent read operations will see this key value pair globally.
- Stores the given
delete(keystring)
Promise<void>
- Deletes the given
value
and metadata under the associatedkey
. Once the delete succeeds, returnsvoid
. - R2 deletes are strongly consistent. Once the Promise resolves, all subsequent read operations will no longer see this key value pair globally.
- Deletes the given
list(optionsR2ListOptions )
Promise<R2Objects|null>
- Returns an
R2Objects
containing a list ofR2Object
contained within the bucket. By default, returns the first 1000 entries.
- Returns an
R2Object definition
keystring
- The object’s key.
bodyReadableStream
- The object’s value.
bodyUsedboolean
- Whether the object’s value has been consumed or not.
arrayBuffer()
Promise<ArrayBuffer
- Returns a Promise that resolves to an ArrayBuffer containing the object’s value.
text()
Promise<string
- Returns a Promise that resolves to an string containing the object’s value.
json
() Promise<T
- Returns a Promise that resolves to the given object containing the object’s value.
blob()
Promise<Blob
- Returns a Promise that resolves to a binary Blob containing the object’s value.
versionstring
- Random unique string associated with a specific upload of a key.
sizenumber
- Size of the object in bytes.
etagstring
- The etag associated with the object upload.
httpEtagstring
- The object’s etag, in quotes so as to be returned as a header.
uploadedDate
- A Date object representing the time the object was uploaded.
httpMetadataR2HTTPMetadata
- Various HTTP headers associated with the object. See HTTP Metadata .
customMetadataRecord<string, string>
- A map of custom, user-defined metadata associated with the object.
Method-specific types
R2GetOptions
onlyIfR2Conditional
- Specifies that the Object should only be returned given satisfaction of certain conditions in the R2Conditional. See Conditional Operations .
Ranged reads
R2GetOptions accepts a range parameter, which restricts data returned in body
to be range
bytes, starting from offset
, inclusive.
offsetnumber
- The byte to begin returning data from, inclusive.
rangenumber
- The number of bytes to return. If more bytes are requested than exist in the object, fewer bytes than this number may be returned.
R2PutOptions
httpMetadataR2HTTPMetadata|Headers
- Various HTTP headers associated with the object. See HTTP Metadata .
customMetadataRecord<string, string>
- A map of custom, user-defined metadata that will be stored with the object.
md5ArrayBufferstring
- A md5 hash to use to check the recieved object’s integrity.
sha1ArrayBufferstring
- A sha1 hash to use to check the recieved object’s integrity.
R2ListOptions
limitnumber
- The number of results to return. Defaults to 1000, with a maximum of 1000.
prefixstring
- The prefix to match keys against. Keys will only be returned if they start with given prefix.
cursorstring
- An opaque token that indicates where to continue listing objects from. A cursor can be retrieved from a previous list operation.
delimiterstring
- The character to use when grouping keys.
includeArray<string>
Can include
httpMetadata
and/orcustomMetadata
. If included, items returned by the list will include the specified metadata.Note that there is a limit on the total amount of data that a single
list
operation can return. If you request data, you may recieve fewer thanlimit
results in your response to accomodate metadata.
This means applications must be careful to avoid code like the following:
while (listed.length < limit) { listed = myBucket.list({ limit, include: ['customMetadata'] }) }
Instead, use the truncated
property to determine if the list
request has more data to be returned.
R2Objects
An object containing an R2Object array, returned by BUCKET_BINDING.list().
objectsArray<
R2Object
>- An array of objects matching the
list
request.
- An array of objects matching the
truncatedboolean
- If true, indicates there are more results to be retrieved for the current
list
request.
- If true, indicates there are more results to be retrieved for the current
cursorstring
- A token that can be passed to future
list
calls to resume listing from that point. Only present if truncated is true.
- A token that can be passed to future
cursordelimitedPrefixes
If a delimiter has been specified, contains all prefixes between the specified prefix and the next occurence of the delimiter.
For example, if no prefix is provided and the delimiter is ‘/’,
foo/bar/baz
would returnfoo
as a delimited prefix. Iffoo/
was passed as a prefix with the same structure and delimiter,foo/bar
would be returned as a delimited prefix.
Conditional operations
You can pass an R2Conditional object to R2GetOptions. If the condition check fails, the body will not be returned. This will make get()
have lower latency.
etagMatchesstring
- Performs the operation if the object’s etag matches the given string.
etagDoesNotMatchstring
- Performs the operation if the object’s etag does not match the given string.
uploadedBeforeDate
- Performs the operation if the object was uploaded before the given date.
uploadedAfterDate
- Performs the operation if the object was uploaded after the given date.
For more information about conditional requests, see RFC 7232.
HTTP Metadata
Generally, these fields match the HTTP metadata passed when the object was created. They can be overriden when issuing get
requests, in which case the given values will be echoed back in the response.
contentTypestring
contentLanguagestring
contentDispositionstring
contentEncodingstring
cacheControlstring
cacheExpiryDate