skip to content

In Cloudflare Workers, how do you write, read and list objects in an R2 bucket through its binding, and what does each call return?

level: juniorimportance: must knowfreq 65%

answer

  1. r2_buckets entry in the Wrangler file
  2. metadata only versus metadata plus body
  3. a missing key is not an exception
  4. truncated and cursor, not counts

basics

~10 s

Bind the bucket under r2_buckets and call env.BUCKET.put(), get(), head(), list() and delete(). put() returns an R2Object, get() an R2ObjectBody with a stream, head() metadata only, and a missing key gives null.

solid answer

~40 s

An `r2_buckets` entry in the Wrangler file binds a bucket to `env`, for example `env.UPLOADS`. `put(key, value, { httpMetadata, customMetadata })` stores a stream, string or buffer and resolves to an `R2Object` carrying `key`, `size`, `etag` and `httpEtag`. `get(key)` resolves to an `R2ObjectBody` whose `body` is a `ReadableStream`, and `head(key)` to an `R2Object` with metadata only; both resolve to `null` for a missing key instead of throwing. `writeHttpMetadata(headers)` copies the stored content type and cache headers onto a response. `list({ prefix, delimiter, cursor, limit })` returns at most 1,000 objects per call, so you page with `truncated` and `cursor`. Writes, deletes and listings are strongly consistent: once `put()` resolves, reads from every location see the new object.

code

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

    if (request.method === "PUT") {
      const object = await env.UPLOADS.put(key, request.body, {
        httpMetadata: { contentType: request.headers.get("content-type") ?? "application/octet-stream" },
        customMetadata: { uploadedBy: "user-42" },
      });
      return Response.json({ key: object.key, size: object.size, etag: object.etag });
    }

    if (request.method === "HEAD") {
      const object = await env.UPLOADS.head(key);
      if (object === null) return new Response(null, { status: 404 });
      const headers = new Headers();
      object.writeHttpMetadata(headers);
      headers.set("etag", object.httpEtag);
      headers.set("content-length", String(object.size));
      return new Response(null, { headers });
    }

    if (request.method === "GET") {
      const object = await env.UPLOADS.get(key);
      if (object === null) return new Response("Not found", { status: 404 });
      const headers = new Headers();
      object.writeHttpMetadata(headers);
      headers.set("etag", object.httpEtag);
      return new Response(object.body, { headers });
    }

    return new Response("Method not allowed", { status: 405, headers: { Allow: "GET, HEAD, PUT" } });
  },
};

go deeper

for a junior

Recall the r2_buckets binding and the five methods, and say plainly that get() and head() resolve to null for a missing key, so the Worker returns the 404.

for a middle

Explain the return types: R2Object from put() and head(), R2ObjectBody with a stream from get(), and how writeHttpMetadata() and httpEtag build the response headers.

for a senior

Show that you page list() on truncated and cursor, ask for metadata with include, and know that writes to one key faster than about one per second are rate limited.

for a principal

Place the binding beside the S3-compatible API: code inside Workers uses the binding and needs no keys, while outside tools need scoped API tokens that someone must issue and rotate.

## Binding a bucket to a Worker A **binding** is a variable the Workers runtime injects into `env`. For R2 you declare it in the Wrangler file with an `r2_buckets` entry: `binding` is the JavaScript name your code uses and `bucket_name` is the bucket it points at. ```json { "r2_buckets": [{ "binding": "UPLOADS", "bucket_name": "user-uploads" }] } ``` The binding carries its own authorisation, so the Worker needs no access keys. Under `wrangler dev` the same binding talks to a local, simulated bucket stored under `.wrangler/state`, which makes everything below easy to try offline. ## Writing objects with put() `env.UPLOADS.put(key, value, options)` stores one object and resolves to an **`R2Object`**, the metadata record for that write. - `value` may be a `ReadableStream` (such as `request.body`), a string, an `ArrayBuffer`, a typed array, a `Blob` or `null`. - `httpMetadata` stores HTTP headers with the object: `contentType`, `contentDisposition`, `contentEncoding`, `contentLanguage`, `cacheControl` and `cacheExpiry`. - `customMetadata` is a string-to-string map of your own fields, such as the uploader's ID; all metadata together is capped at 8,192 bytes. - An optional checksum (`md5`, `sha1`, `sha256`, `sha384` or `sha512`, one at a time) makes R2 reject a body that does not match. - `storageClass` picks `Standard` or `InfrequentAccess` for this object; without it the bucket's default applies. The returned `R2Object` includes `key`, `size`, `uploaded`, `version` (a random string unique to this upload), `etag` (bare hex) and `httpEtag` (the same value in quotes, ready for an `ETag` header). ## Reading: get(), head() and the null case | Call | Resolves to | Body transferred | |---|---|---| | `get(key)` | `R2ObjectBody`, or `null` if absent | yes, as `body` (a `ReadableStream`) | | `head(key)` | `R2Object`, or `null` if absent | no | | `get(key, { onlyIf })` with a failed condition | `R2Object` without `body` | no | `R2ObjectBody` adds `body`, `bodyUsed` and the helpers `text()`, `json()`, `arrayBuffer()` and `blob()` to every `R2Object` field. A missing key is **not an exception**: code must check for `null` and answer 404 itself. To serve an object, create a `Headers`, call `object.writeHttpMetadata(headers)` to copy the stored HTTP metadata, set `etag` from `httpEtag`, and return `new Response(object.body, { headers })`; the stream flows to the client without being buffered in the isolate's memory. ## Listing and deleting `list(options)` resolves to an `R2Objects` result: `objects`, `truncated`, `cursor` (present only when `truncated` is true) and `delimitedPrefixes`. - `limit` defaults to 1,000, which is also the maximum per call. - `prefix` keeps keys that start with it; R2 returns keys in lexicographic order. - `delimiter` (usually `/`) groups deeper keys into `delimitedPrefixes`, so listing `avatars/` with `/` returns `avatars/u1/` and `avatars/u2/` instead of every photo. - `include: ["httpMetadata", "customMetadata"]` asks for metadata on each listed object; with a compatibility date from 2022-08-04 onward, leaving it out returns empty metadata. - A call can return **fewer** objects than `limit` to save memory, especially with `include`. So the paging loop is: 1. Call `list()` with your options. 2. Process `objects`. 3. While `truncated` is true, call `list()` again with the same options plus `cursor`. `delete(keys)` takes one key or an array of up to 1,000 keys and resolves once they are gone. ## Consistency and limits worth knowing R2 is **strongly consistent**: when `put()` or `delete()` resolves, every later read and listing, from any location, sees the change. Two writers to the same key do not merge; the last one to complete wins, and writes to one key faster than about one per second are rate limited (HTTP 429). A single `put()` stores up to 5 GiB (larger objects need a multipart upload, up to about 5 TiB), and keys are limited to 1,024 bytes. Each `put()` and `list()` is a Class A operation, each `get()` and `head()` a Class B operation, deletes are free, and reading data out of R2 carries no egress charge. ## Binding or S3-compatible API? The same bucket is also reachable through R2's **S3-compatible API** at `https://<ACCOUNT_ID>.r2.cloudflarestorage.com` with region `auto`, which is what backup tools, an S3-compatible client in another service, or a presigned URL use. - Inside a Worker, prefer the binding: no access keys to store, no signing, and results as JavaScript objects. - Outside Workers, the S3 API needs an R2 API token's Access Key ID and Secret Access Key. - The two differ in places: the binding reports a missing key as `null` and a failed precondition as `null` or a body-less object, where the S3 API answers with HTTP errors such as `NoSuchKey` or `PreconditionFailed`.

  • Why should a Worker send object.httpEtag rather than object.etag in an ETag response header?
    `etag` is the bare hex value, while `httpEtag` wraps it in quotes as an HTTP entity tag must be, so browsers and caches can echo it in `If-None-Match` or `If-Match`. Keep the bare `etag` for the binding's own `onlyIf: { etagMatches }`, which rejects a quoted value with a `TypeError`.
  • How do you list the per-user folders under avatars/ in an R2 bucket without listing every photo?
    Call `list({ prefix: "avatars/", delimiter: "/" })`. Keys deeper than the next `/` are folded into `delimitedPrefixes`, such as `avatars/u1/` and `avatars/u2/`, and `objects` holds only keys sitting directly under the prefix. The result can still be truncated, so keep paging with `cursor` while `truncated` is true.
  • A Worker lists an R2 prefix and every object's customMetadata comes back empty. What is missing?
    The `include` option. On compatibility dates from 2022-08-04, `list()` returns `httpMetadata` and `customMetadata` only when asked with `include: ["customMetadata"]` (or both names). Requesting metadata can shrink each page, which is another reason to page on `truncated` rather than on the count.

  • env.BUCKET.get() throws an exception when the key does not exist
  • head() downloads the object body along with its metadata
  • Keep calling list() until objects.length is smaller than the limit
  • R2 writes take up to a minute to appear in other locations
  • list() always returns customMetadata without being asked for it