Workers API reference (2)

Last updated Jul 31, 2026 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.

Create a binding

Bindings

A binding is how your Worker interacts with external resources such as KV Namespaces, Durable Objects, or R2 Buckets. A binding is a runtime variable that the Workers runtime provides to your code. You can declare a variable name in your Wrangler file that will be bound to these resources at runtime, and interact with them through this variable. Every binding's variable name and behavior is determined by you when deploying the Worker. Refer to Environment Variables for more information.

A binding is defined in the Wrangler file of your Worker project's directory.

To bind your R2 bucket to your Worker, add the following to your Wrangler 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>"
        }
    ]
}
[[r2_buckets]]
binding = "MY_BUCKET"
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:

export default {
    async fetch(request, env) {
        const url = new URL(request.url);
        const key = url.pathname.slice(1);

switch (request.method) {
            case "PUT":
                await env.MY_BUCKET.put(key, request.body);
                return new Response(`Put ${key} successfully!`);

default:
                return new Response(`${request.method} is not allowed.`, {
                    status: 405,
                    headers: {
                        Allow: "PUT",
                    },
                });
        }
    },
};
from workers import WorkerEntrypoint, Response
from urllib.parse import urlparse

class Default(WorkerEntrypoint):
    async def fetch(self, request):
        url = urlparse(request.url)
        key = url.path[1:]

if request.method == "PUT":
            await self.env.MY_BUCKET.put(key, request.body)
            return Response(f"Put {key} successfully!")
        else:
            return Response(
                f"{request.method} is not allowed.",
                status=405,
                headers={"Allow": "PUT"}
            )
  • head (key: string): 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 (key: string, options?: R2GetOptions): Promise<R2ObjectBody | R2Object | null>
  • Retrieves the R2ObjectBody 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 an R2Object with body undefined.
  • put (key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise<R2Object | null>
  • Stores the given value and metadata under the associated key. Once the write succeeds, returns an R2Object containing metadata about the stored Object.
  • In the event that a precondition specified in options fails, put() returns null, and the object will not be stored.
  • R2 writes are strongly consistent. Once the Promise resolves, all subsequent read operations will see this key value pair globally.
  • delete (key: string | string[]): Promise<void>
  • Deletes the given values and metadata under the associated keys. Once the delete succeeds, returns void.
  • R2 deletes are strongly consistent. Once the Promise resolves, all subsequent read operations will no longer see the provided key value pairs globally.
  • Up to 1000 keys may be deleted per call.
  • list (options?: R2ListOptions): Promise<R2Objects>
  • Returns an R2Objects containing a list of R2Object contained within the bucket.
  • The returned list of objects is ordered lexicographically.
  • Returns up to 1000 entries, but may return less in order to minimize memory pressure within the Worker.
  • To explicitly set the number of objects to list, provide an R2ListOptions object with the limit property set.

  • createMultipartUpload (key: string, options?: R2MultipartOptions): Promise<R2MultipartUpload>

  • Creates a multipart upload.
  • Returns Promise which resolves to an R2MultipartUpload object representing the newly created multipart upload. Once the multipart upload has been created, the multipart upload can be immediately interacted with globally, either through the Workers API, or through the S3 API.

  • resumeMultipartUpload (key: string, uploadId: string): R2MultipartUpload

  • Returns an object representing a multipart upload with the given key and uploadId.
  • The resumeMultipartUpload operation does not perform any checks to ensure the validity of the uploadId, nor does it verify the existence of a corresponding active multipart upload. This is done to minimize latency before being able to call subsequent operations on the R2MultipartUpload object.

R2Object definition

R2Object is created when you PUT an object into an R2 bucket. R2Object represents the metadata of an object based on the information provided by the uploader. Every object that you PUT into an R2 bucket will have an R2Object created.

  • key string
  • The object's key.
  • version string
  • Random unique string associated with a specific upload of a key.
  • size number
  • Size of the object in bytes.
  • etag string

Note

Cloudflare recommends using the httpEtag field when returning an etag in a response header. This ensures the etag is quoted and conforms to RFC 9110 ↗︎.

  • The etag associated with the object upload.
  • httpEtag string
  • The object's etag, in quotes so as to be returned as a header.
  • uploaded Date
  • A Date object representing the time the object was uploaded.
  • httpMetadata R2HTTPMetadata
  • Various HTTP headers associated with the object. Refer to HTTP Metadata.
  • customMetadata Record<string, string>
  • A map of custom, user-defined metadata associated with the object.
  • range R2Range optional
  • A R2Range object containing the returned range of the object.
  • checksums R2Checksums
  • A R2Checksums object containing the stored checksums of the object. Refer to checksums.
  • writeHttpMetadata (headers: Headers): void
  • Retrieves the httpMetadata from the R2Object and applies their corresponding HTTP headers to the Headers input object. Refer to HTTP Metadata.
  • storageClass 'Standard' | 'InfrequentAccess'
  • The storage class associated with the object. Refer to Storage Classes.
  • ssecKeyMd5 string optional
  • Hex-encoded MD5 hash of the SSE-C key used for encryption (if one was provided). Hash can be used to identify which key is needed to decrypt object.

R2ObjectBody definition

R2ObjectBody represents an object's metadata combined with its body. It is returned when you GET an object from an R2 bucket. The full list of keys for R2ObjectBody includes the list below and all keys inherited from R2Object.

  • body ReadableStream
  • The object's value.
  • bodyUsed boolean
  • 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 a string containing the object's value.
  • json <T>() : 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.

R2MultipartUpload definition

An R2MultipartUpload object is created when you call createMultipartUpload or resumeMultipartUpload. R2MultipartUpload is a representation of an ongoing multipart upload.

Uncompleted multipart uploads will be automatically aborted after 7 days.

Note

An R2MultipartUpload object does not guarantee that there is an active underlying multipart upload corresponding to that object.

A multipart upload can be completed or aborted at any time, either through the S3 API, or by a parallel invocation of your Worker. Therefore it is important to add the necessary error handling code around each operation on a R2MultipartUpload object in case the underlying multipart upload no longer exists.

  • key string
  • The key for the multipart upload.
  • uploadId string
  • The uploadId for the multipart upload.
  • uploadPart (partNumber: number, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | Blob, options?: R2MultipartOptions): Promise<R2UploadedPart>
  • Uploads a single part with the specified part number to this multipart upload. Each part must be uniform in size with an exception for the final part which can be smaller.
  • Returns an R2UploadedPart object containing the etag and partNumber. These R2UploadedPart objects are required when completing the multipart upload.
  • abort (): Promise<void>
  • Aborts the multipart upload. Returns a Promise that resolves when the upload has been successfully aborted.
  • complete (uploadedParts: R2UploadedPart[]): Promise<R2Object>
  • Completes the multipart upload with the given parts.
  • Returns a Promise that resolves when the complete operation has finished. Once this happens, the object is immediately accessible globally by any subsequent read operation.

Method-specific types

R2GetOptions

  • onlyIf R2Conditional | Headers
  • Specifies that the object should only be returned given satisfaction of certain conditions in the R2Conditional or in the conditional Headers. Refer to Conditional operations.
  • range R2Range | Headers optional
  • Specifies that only a specific length (from an optional offset) or suffix of bytes from the object should be returned given the range in the R2Range or in the range Headers. Refer to Ranged reads.
  • ssecKey ArrayBuffer | string
  • Specifies a key to be used for SSE-C. Key must be 32 bytes in length, in the form of a hex-encoded string or an ArrayBuffer.

Ranged reads

R2GetOptions accepts a range parameter, which can be used to restrict the data returned in body.

There are 3 variations of arguments that can be used in a range: