Cloud and deployment · Intermediate · 24 min
Store and serve files with Cloudflare R2 from a Worker
By Padding · Updated 18 Nov 2026
Debian (node:26 image) · Node.js 26.13.1 · Wrangler 4.168.0 · Vitest 4.1.12 · @cloudflare/vitest-plugin 1.9.2
You will build a Worker that uploads, downloads and lists files in an R2 bucket, with a size limit, a content-type allowlist, ETag and range support and a bearer token, test it locally with Wrangler and Vitest, and reach the same bucket through R2's S3-compatible API.
On this page
R2 is Cloudflare's object storage. You keep files in a bucket, the way you would in Amazon S3, and a Worker reaches the bucket through a binding: an object on env with put, get, head, list and delete methods, with no keys or endpoints in your code. The same bucket also speaks the S3 API, so the AWS CLI and S3 SDKs work against it with an R2 API token.
You will build a small file service on one Worker:
PUT /files/<name>stores a file. It needs a bearer token, accepts only a few content types and refuses anything over 1 MiB.GET /files/<name>serves it, with anETagso a client can ask "has it changed?" and get a tiny304back, and with range support so a download that drops halfway can carry on from where it stopped.GET /fileslists what is stored, also behind the token.
Those last two matter more than they look. On a phone with prepaid data, or a connection that drops on a moving bus, re-downloading a whole file because the last 10% failed costs real money. Range requests and ETags are how a client avoids that.
Everything up to the deploy step runs on your machine. wrangler dev simulates R2 on disk, so you need no Cloudflare account until you want the bucket online.
Step 1 · Create the project
Make a throwaway folder and write a package.json with exact versions. Wrangler runs the Worker, Vitest runs the tests, and @cloudflare/vitest-plugin makes the tests run inside the same Workers runtime as production. That plugin is the new name of @cloudflare/vitest-pool-workers, which is deprecated, so older guides that use the old name still apply with the new import.
mkdir -p ~/r2-files-demo
cd ~/r2-files-demo
cat > package.json <<'JSON'
{
"name": "r2-files-demo",
"private": true,
"type": "module",
"scripts": {
"dev": "wrangler dev",
"test": "vitest run",
"deploy": "wrangler deploy"
},
"devDependencies": {
"@cloudflare/vitest-plugin": "1.9.2",
"vitest": "4.1.12",
"wrangler": "4.168.0"
}
}
JSON
npm install
printf 'node_modules\n.wrangler\n.dev.vars\nauth-header.txt\n' > .gitignoreThe .gitignore keeps out the local bucket data that Wrangler writes under .wrangler/, and the two files that will hold your token.
Check it worked
npx wrangler --version
npm ls vitest @cloudflare/vitest-pluginWrangler prints a version line containing 4.168.0, and the tree lists vitest@4.1.12 and @cloudflare/vitest-plugin@1.9.2 with no UNMET or invalid lines.
Step 2 · Bind a bucket and set the upload token
Create wrangler.jsonc. The r2_buckets entry says: inside the Worker, env.FILES is the bucket named r2-files-demo. The binding name is what your code uses; the bucket name is what exists in your account. Keeping them separate means you can point the same code at a different bucket without touching it.
cat > wrangler.jsonc <<'JSONC'
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "r2-files-demo",
"main": "src/index.ts",
"compatibility_date": "2026-11-01",
"r2_buckets": [
{ "binding": "FILES", "bucket_name": "r2-files-demo" }
]
}
JSONCThe upload token is a secret, so it never goes in wrangler.jsonc or in your code. Locally, Wrangler reads it from .dev.vars. Generate a random value and write it into a file that is private from the moment it exists, then write a second private file that holds the matching Authorization header for curl. That way the token never appears on a command line or in your shell history:
(
umask 077
token="$(node -e 'console.log(require("node:crypto").randomBytes(32).toString("hex"))')"
printf 'UPLOAD_TOKEN=%s\n' "$token" > .dev.vars
printf 'Authorization: Bearer %s\n' "$token" > auth-header.txt
)The parentheses run the block in a subshell, so the umask and the token variable vanish when it ends.
Check it worked
ls -l .dev.vars auth-header.txt
grep -c '^UPLOAD_TOKEN=' .dev.varsBoth files show -rw------- (readable only by you), and grep prints 1.
Step 3 · Write the upload handler
Create src/limits.ts with the rules, kept apart so the tests can import them, and src/index.ts with the routing, the token check and the upload. The download and list functions come in the next step, in the same file.
Three decisions shape the upload:
- Content types are an allowlist. Plain text, PNG, JPEG, WebP and PDF are accepted. HTML and SVG are left out on purpose: a file served from your domain that a browser renders as a page can run scripts as your site.
- The size limit is enforced twice. A
Content-Lengthover the limit is refused before any of the body is read. The body is then read through a counter that stops at the limit, which also covers clients that send no length. R2'sput()needs a body of known length anyway, and buffering a capped 1 MiB is cheap. - The token is compared in constant time. Both values are hashed with SHA-256 and compared with
crypto.subtle.timingSafeEqual, a Workers addition to Web Crypto, so the time a wrong guess takes says nothing about how close it was.
mkdir -p src
cat > src/limits.ts <<'TS'
export const MAX_BYTES = 1024 * 1024; // 1 MiB
export const ALLOWED_TYPES = new Set(["text/plain", "image/png", "image/jpeg", "image/webp", "application/pdf"]);
export const KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
TS
cat > src/index.ts <<'TS'
import { ALLOWED_TYPES, KEY_PATTERN, MAX_BYTES } from "./limits";
interface Env {
FILES: R2Bucket;
UPLOAD_TOKEN: string;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === "/files") {
if (request.method !== "GET") return text("method not allowed", 405, { Allow: "GET" });
if (!(await authorised(request, env))) return unauthorised();
return listFiles(url, env);
}
const match = url.pathname.match(/^\/files\/([^/]+)$/);
if (!match) return text("not found", 404);
const key = match[1];
if (!KEY_PATTERN.test(key)) return text("invalid file name", 400);
switch (request.method) {
case "GET":
return getFile(request, env, key);
case "PUT":
if (!(await authorised(request, env))) return unauthorised();
return putFile(request, env, key);
case "DELETE":
if (!(await authorised(request, env))) return unauthorised();
await env.FILES.delete(key);
return new Response(null, { status: 204 });
default:
return text("method not allowed", 405, { Allow: "GET, PUT, DELETE" });
}
},
};
async function authorised(request: Request, env: Env): Promise<boolean> {
const header = request.headers.get("Authorization") ?? "";
const given = header.startsWith("Bearer ") ? header.slice(7) : "";
if (!given || !env.UPLOAD_TOKEN) return false;
const encoder = new TextEncoder();
const [a, b] = await Promise.all([
crypto.subtle.digest("SHA-256", encoder.encode(given)),
crypto.subtle.digest("SHA-256", encoder.encode(env.UPLOAD_TOKEN)),
]);
return crypto.subtle.timingSafeEqual(a, b);
}
async function putFile(request: Request, env: Env, key: string): Promise<Response> {
const type = (request.headers.get("Content-Type") ?? "").split(";")[0].trim().toLowerCase();
if (!ALLOWED_TYPES.has(type)) return text("unsupported content type", 415);
const declared = Number(request.headers.get("Content-Length") ?? "0");
if (declared > MAX_BYTES) return text("file too large", 413);
const body = await readLimited(request.body, MAX_BYTES);
if (!body) return text("file too large", 413);
const object = await env.FILES.put(key, body, { httpMetadata: { contentType: type } });
if (!object) return text("upload failed", 500);
return Response.json(
{ key: object.key, size: object.size, etag: object.httpEtag },
{ status: 201, headers: { ETag: object.httpEtag } },
);
}
// Read a request body, giving up as soon as it passes `max` bytes.
async function readLimited(stream: ReadableStream<Uint8Array> | null, max: number): Promise<Uint8Array | null> {
if (!stream) return new Uint8Array();
const reader = stream.getReader();
const chunks: Uint8Array[] = [];
let total = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
total += value.byteLength;
if (total > max) {
await reader.cancel();
return null;
}
chunks.push(value);
}
const out = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
out.set(chunk, offset);
offset += chunk.byteLength;
}
return out;
}
function unauthorised(): Response {
return text("unauthorised", 401, { "WWW-Authenticate": "Bearer" });
}
function text(body: string, status: number, extra: Record<string, string> = {}): Response {
return new Response(body + "\n", {
status,
headers: { "Content-Type": "text/plain; charset=utf-8", ...extra },
});
}
TSFile names are restricted to letters, digits, dots, hyphens and underscores, up to 128 characters, with no slashes. That keeps the routing simple and stops names such as ../x from meaning anything. R2 itself allows slashes in keys, and you can widen the pattern later if you want folders.
The interface Env block is for your editor only. Wrangler and Vitest remove TypeScript types without checking them. If you want full editor types for R2Bucket and friends, npx wrangler types generates them from your config.
Check it worked
grep -c 'async function' src/index.tsThe count is 3: authorised, putFile and readLimited. The file does not run yet, because getFile and listFiles are still missing.
Step 4 · Serve downloads with ETags and ranges, and list files
Append the download and list handlers. A download first calls head(), which returns the object's size, ETag and stored content type without the body. That one cheap call decides everything:
- No object:
404. - The client sent
If-None-Matchwith the current ETag:304 Not Modifiedand no body. The client uses its saved copy. - The client sent
Range: bytes=start-end:206 Partial Contentwith only those bytes and aContent-Rangeheader, or416if the range starts past the end of the file. - Otherwise:
200and the whole file.
Ranges this code does not understand, such as several ranges in one header, are ignored and the whole file is sent. The HTTP standard allows that, and it keeps the parser short.
cat >> src/index.ts <<'TS'
async function getFile(request: Request, env: Env, key: string): Promise<Response> {
const head = await env.FILES.head(key);
if (!head) return text("not found", 404);
const headers = new Headers();
head.writeHttpMetadata(headers);
headers.set("ETag", head.httpEtag);
headers.set("Accept-Ranges", "bytes");
headers.set("Cache-Control", "no-cache");
headers.set("X-Content-Type-Options", "nosniff");
if (etagMatches(request.headers.get("If-None-Match"), head.httpEtag)) {
return new Response(null, { status: 304, headers });
}
const range = parseRange(request.headers.get("Range"), head.size);
if (range === "unsatisfiable") {
headers.set("Content-Range", `bytes */${head.size}`);
return new Response(null, { status: 416, headers });
}
if (range === "whole") {
const object = await env.FILES.get(key);
if (!object) return text("not found", 404);
return new Response(object.body, { status: 200, headers });
}
const object = await env.FILES.get(key, { range });
if (!object) return text("not found", 404);
const last = range.offset + range.length - 1;
headers.set("Content-Range", `bytes ${range.offset}-${last}/${head.size}`);
return new Response(object.body, { status: 206, headers });
}
function etagMatches(header: string | null, etag: string): boolean {
if (!header) return false;
return header.split(",").some((tag) => {
const value = tag.trim().replace(/^W\//, "");
return value === "*" || value === etag;
});
}
type Range = { offset: number; length: number };
// Understands "bytes=10-19", "bytes=10-" and "bytes=-10" (the last ten bytes).
function parseRange(header: string | null, size: number): Range | "whole" | "unsatisfiable" {
if (!header) return "whole";
const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
if (!match || (match[1] === "" && match[2] === "")) return "whole";
if (match[1] === "") {
const wanted = Math.min(Number(match[2]), size);
return wanted > 0 ? { offset: size - wanted, length: wanted } : "unsatisfiable";
}
const start = Number(match[1]);
const end = match[2] === "" ? size - 1 : Math.min(Number(match[2]), size - 1);
if (start >= size || end < start) return "unsatisfiable";
return { offset: start, length: end - start + 1 };
}
async function listFiles(url: URL, env: Env): Promise<Response> {
const asked = Number(url.searchParams.get("limit")) || 100;
const limit = Math.min(Math.max(asked, 1), 1000);
const listed = await env.FILES.list({
limit,
prefix: url.searchParams.get("prefix") ?? undefined,
cursor: url.searchParams.get("cursor") ?? undefined,
include: ["httpMetadata"],
});
return Response.json({
files: listed.objects.map((o) => ({
key: o.key,
size: o.size,
type: o.httpMetadata?.contentType ?? null,
etag: o.httpEtag,
uploaded: o.uploaded.toISOString(),
})),
cursor: listed.truncated ? listed.cursor : null,
});
}
TSlist() returns at most 1,000 objects per call. When there are more, truncated is true and the response carries a cursor. The client passes it back as ?cursor=... to get the next page, so a bucket with a million files never turns into one huge response.
Cache-Control: no-cache does not mean "do not cache". It means "keep a copy, but check with me before using it", which is exactly what the ETag check answers cheaply.
Check it worked
grep -c 'async function' src/index.ts
grep -n 'status: 206' src/index.tsThe count is now 5, and grep shows the line that returns 206.
Step 5 · Run it locally with Wrangler
Start the dev server in your second terminal, from the project folder, and leave it running:
npm run devWrangler prints that the Worker is ready on http://localhost:8787, and its list of bindings shows env.FILES as an R2 bucket in local mode, in something like those words. Nothing in the account is touched. Back in the first terminal, make a small file and try to upload it without the token, then with it:
printf 'Hello from R2. 0123456789\n' > hello.txt
curl -s -X PUT -H 'Content-Type: text/plain' --data-binary @hello.txt http://localhost:8787/files/hello.txt
curl -s -X PUT -H @auth-header.txt -H 'Content-Type: text/plain' --data-binary @hello.txt http://localhost:8787/files/hello.txt
echo
curl -s http://localhost:8787/files/hello.txt-H @auth-header.txt makes curl read the header from the file, and --data-binary sends the file byte for byte, where -d would strip newlines.
Check it worked
The first upload prints unauthorised. The second prints JSON such as {"key":"hello.txt","size":26,"etag":"\"…\""}. The download prints Hello from R2. 0123456789.
Step 6 · Try the limits, ETags and ranges
Now prove each rule does its job. Try an HTML file, a 2 MiB file and a bad name. -w '%{http_code}\n' prints only the status code:
printf '<p>hi</p>\n' > page.html
head -c 2097152 /dev/zero > big.bin
curl -s -o /dev/null -w '%{http_code}\n' -X PUT -H @auth-header.txt -H 'Content-Type: text/html' --data-binary @page.html http://localhost:8787/files/page.html
curl -s -o /dev/null -w '%{http_code}\n' -X PUT -H @auth-header.txt -H 'Content-Type: text/plain' --data-binary @big.bin http://localhost:8787/files/big.txt
curl -s -o /dev/null -w '%{http_code}\n' -X PUT -H @auth-header.txt -H 'Content-Type: text/plain' --data-binary @hello.txt 'http://localhost:8787/files/.hidden'Next, the conditional request. Save the ETag from a first download, then ask again with If-None-Match, the way a browser or app does on its second visit. Then ask for bytes 15 to 24 only, and for a range past the end:
etag="$(curl -s -o /dev/null -w '%header{etag}' http://localhost:8787/files/hello.txt)"
echo "ETag: $etag"
curl -s -o /dev/null -w '%{http_code}\n' -H "If-None-Match: $etag" http://localhost:8787/files/hello.txt
curl -s -i -H 'Range: bytes=15-24' http://localhost:8787/files/hello.txt | grep -i -E '^(HTTP|content-range)|^[0-9]'
curl -s -o /dev/null -w '%{http_code}\n' -H 'Range: bytes=500-' http://localhost:8787/files/hello.txtFinally, list the bucket with and without the token:
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8787/files
curl -s -H @auth-header.txt http://localhost:8787/files
echoCheck it worked
The three uploads print 415, 413 and 400, so nothing was stored. The ETag is a quoted hex string, and asking with it prints 304. The range request shows a 206 status line, content-range: bytes 15-24/26 and the body 0123456789. The range past the end prints 416. The list prints 401 without the token, and with it a JSON object whose files array holds only hello.txt, with "type":"text/plain", and "cursor":null.
Step 7 · Write tests that run in the Workers runtime
curl checks are good for exploring but you will not repeat them by hand. Vitest with the Cloudflare plugin runs your tests inside workerd, with a local R2 bucket of their own, so the same rules are checked on every change in a second or two.
The config points the plugin at wrangler.jsonc, so the tests get the same FILES binding. It also sets UPLOAD_TOKEN to a fixed test value. The tests read the token from env rather than hard-coding it, so they keep working whichever value the runtime ends up with.
cat > vitest.config.ts <<'TS'
import { cloudflareTest } from "@cloudflare/vitest-plugin";
import { defineConfig } from "vitest/config";
export default defineConfig({
plugins: [
cloudflareTest({
wrangler: { configPath: "./wrangler.jsonc" },
miniflare: { bindings: { UPLOAD_TOKEN: "test-token-not-a-secret" } },
}),
],
});
TS
mkdir -p test
cat > test/files.test.ts <<'TS'
import { env, exports } from "cloudflare:workers";
import { describe, expect, it } from "vitest";
import { MAX_BYTES } from "../src/limits";
const BASE = "https://files.example";
function auth(): Record<string, string> {
return { Authorization: `Bearer ${env.UPLOAD_TOKEN}` };
}
function upload(key: string, body: string, type = "text/plain") {
return exports.default.fetch(`${BASE}/files/${key}`, {
method: "PUT",
headers: { ...auth(), "Content-Type": type },
body,
});
}
describe("uploads", () => {
it("needs the token", async () => {
const res = await exports.default.fetch(`${BASE}/files/a.txt`, {
method: "PUT",
headers: { "Content-Type": "text/plain", Authorization: "Bearer wrong" },
body: "x",
});
expect(res.status).toBe(401);
});
it("refuses types outside the allowlist", async () => {
expect((await upload("a.html", "<p>hi</p>", "text/html")).status).toBe(415);
});
it("refuses files over the limit", async () => {
expect((await upload("big.txt", "x".repeat(MAX_BYTES + 1))).status).toBe(413);
});
it("stores the file and its content type", async () => {
expect((await upload("note.txt", "hello")).status).toBe(201);
const stored = await env.FILES.get("note.txt");
expect(await stored?.text()).toBe("hello");
expect(stored?.httpMetadata?.contentType).toBe("text/plain");
});
});
describe("downloads", () => {
it("answers 304 when the ETag still matches", async () => {
await upload("e.txt", "same");
const first = await exports.default.fetch(`${BASE}/files/e.txt`);
const etag = first.headers.get("ETag");
expect(etag).toBeTruthy();
await first.text();
const second = await exports.default.fetch(`${BASE}/files/e.txt`, {
headers: { "If-None-Match": etag! },
});
expect(second.status).toBe(304);
});
it("serves a byte range", async () => {
await upload("r.txt", "0123456789");
const res = await exports.default.fetch(`${BASE}/files/r.txt`, { headers: { Range: "bytes=2-5" } });
expect(res.status).toBe(206);
expect(res.headers.get("Content-Range")).toBe("bytes 2-5/10");
expect(await res.text()).toBe("2345");
const tail = await exports.default.fetch(`${BASE}/files/r.txt`, { headers: { Range: "bytes=-3" } });
expect(await tail.text()).toBe("789");
const past = await exports.default.fetch(`${BASE}/files/r.txt`, { headers: { Range: "bytes=50-" } });
expect(past.status).toBe(416);
});
it("returns 404 for a missing file", async () => {
expect((await exports.default.fetch(`${BASE}/files/missing.txt`)).status).toBe(404);
});
});
describe("listing", () => {
it("needs the token and lists stored files", async () => {
await upload("l.txt", "list me");
expect((await exports.default.fetch(`${BASE}/files`)).status).toBe(401);
const res = await exports.default.fetch(`${BASE}/files`, { headers: auth() });
const data = (await res.json()) as { files: { key: string }[] };
expect(data.files.map((f) => f.key)).toContain("l.txt");
});
});
TS
npm testexports.default.fetch() calls your Worker's fetch handler the way a real request would, and env.FILES lets a test look inside the bucket directly, as the "stores the file" test does. The tests use their own local storage, separate from the bucket wrangler dev wrote to.
Check it worked
Vitest reports Test Files 1 passed (1) and Tests 8 passed (8). Change MAX_BYTES in src/limits.ts to a smaller value and the size test still passes, because it reads the limit from the source. Change "text/plain" in ALLOWED_TYPES to something else and run npm test again: the storage test fails, which is how you know the tests are really checking the code.
Step 8 · Look inside the local bucket
Stop the dev server with Ctrl+C in the second terminal. The files you uploaded are still on disk under .wrangler/state, and Wrangler's R2 commands can read them. --local is spelled out so the command can never touch a real bucket by mistake, and --pipe writes the file to standard output:
npx wrangler r2 object get r2-files-demo/hello.txt --local --pipeStart npm run dev again later and hello.txt is still there. Delete the .wrangler folder to start with an empty local bucket.
Check it worked
The command prints Hello from R2. 0123456789, the file you uploaded through the Worker.
Step 9 · Create the bucket and deploy
From here on you need a Cloudflare account. Log in, create the real bucket with the name in wrangler.jsonc, store the token as a Worker secret, and deploy. wrangler secret put prompts for the value, so it stays out of your shell history. Use a new random value for production, not the one in .dev.vars:
npx wrangler login
npx wrangler r2 bucket create r2-files-demo
npx wrangler secret put UPLOAD_TOKEN
npm run deployWrangler prints the Worker's address, something like https://r2-files-demo.<your-subdomain>.workers.dev. Make a production header file the same private way as before (umask 077, then write Authorization: Bearer <your production token> into prod-auth-header.txt with your editor), and upload. Replace the address with yours:
curl -s -X PUT -H @prod-auth-header.txt -H 'Content-Type: text/plain' --data-binary @hello.txt https://r2-files-demo.<your-subdomain>.workers.dev/files/hello.txtOn cost, as of 26 November 2026 Cloudflare's R2 pricing page lists Standard storage at USD 0.015 per GB-month, Class A operations (writes and lists) at USD 4.50 per million and Class B operations (reads) at USD 0.36 per million, with a monthly free allowance of 10 GB-month of storage, 1 million Class A and 10 million Class B operations. Data leaving R2 has no egress charge, whether it goes out through a Worker, the S3 API or an r2.dev address. Check the page before you plan around those numbers. Workers requests are billed separately under your Workers plan.
Check it worked
npx wrangler r2 bucket list shows r2-files-demo. The curl upload prints JSON with "key":"hello.txt", and opening https://r2-files-demo.<your-subdomain>.workers.dev/files/hello.txt in a browser shows the text.
Step 10 · Use the S3-compatible API with a scoped token
Any S3 tool can talk to the same bucket. Give it the narrowest access that works. In the Cloudflare dashboard, open R2 object storage, then Manage next to API Tokens, and create a token with the Object Read & Write permission limited to the r2-files-demo bucket only. Cloudflare shows an Access Key ID and a Secret Access Key. The secret is shown once, so copy both before leaving the page.
Store them in a separate AWS CLI profile. aws configure prompts for each value, so nothing lands in your history. Enter auto as the region, which R2 accepts because it does not use AWS regions, and json as the output format:
aws configure --profile r2Your account ID is in the dashboard, on the R2 overview page. Put the endpoint in a variable (replace <ACCOUNT_ID>), then list the bucket, upload a file and make a download link that works for one hour:
R2_ENDPOINT="https://<ACCOUNT_ID>.r2.cloudflarestorage.com"
aws s3 ls s3://r2-files-demo --endpoint-url "$R2_ENDPOINT" --profile r2
aws s3 cp hello.txt s3://r2-files-demo/from-cli.txt --content-type text/plain --endpoint-url "$R2_ENDPOINT" --profile r2
aws s3 presign s3://r2-files-demo/from-cli.txt --expires-in 3600 --endpoint-url "$R2_ENDPOINT" --profile r2The Worker and the S3 API see the same objects. from-cli.txt is now also served by GET /files/from-cli.txt on your Worker. Because the token is scoped to one bucket, a leaked key cannot read or delete anything else in your account. The presigned link is a bearer credential for that hour: do not paste it into logs or public chats. Share private S3 files with presigned URLs covers that pattern in depth, and it applies to R2 with the endpoint changed.
Check it worked
aws s3 ls lists hello.txt. After the copy it also lists from-cli.txt, and curl -s https://r2-files-demo.<your-subdomain>.workers.dev/files/from-cli.txt prints its text. Try aws s3 ls --endpoint-url "$R2_ENDPOINT" --profile r2 with no bucket name: an Object Read & Write token has no permission to list buckets, so expect an access error, which shows the scope is working.
Step 11 · Clean up
If you deployed, remove the remote pieces first, from the project folder so Wrangler can read wrangler.jsonc. Delete the objects, then the bucket, then the Worker. Then revoke the R2 API token in the dashboard under Manage API Tokens, and remove the r2 profile from ~/.aws/credentials and ~/.aws/config:
npx wrangler r2 object delete r2-files-demo/hello.txt --remote
npx wrangler r2 object delete r2-files-demo/from-cli.txt --remote
npx wrangler r2 bucket delete r2-files-demo
npx wrangler deleteNow remove the local project. This deletes the local bucket data and both token files:
cd ~
rm -rf ~/r2-files-demoCheck it worked
test ! -d ~/r2-files-demo && echo "local project removed"The command prints local project removed. If you deployed, npx wrangler r2 bucket list no longer shows r2-files-demo, and the workers.dev address answers with an error page instead of your file.
Next steps
- If you have not deployed a Worker before, start with Build, test and deploy a Cloudflare Worker with Wrangler.
- Let browsers upload straight to the bucket without passing through your Worker: Share private S3 files safely with presigned URLs.
- Put a router and validation in front of these handlers with Build a small API with Hono, which runs on Workers unchanged.
- Serve a static front end for the file service from Cloudflare Pages.
Related tutorials
- Tag cloud resources so you know what costs whatYou will have a four-key tagging scheme applied to every AWS resource through Terraform default_tags, a script that lists resources missing a tag, a tag policy ready for your organisation and cost allocation tags that split the bill by project.
- Store container images in Amazon ECR with scanning and lifecycle policiesYou will have a private Amazon ECR repository with immutable tags and scan on push, an nginx image copied into it with crane, its vulnerability findings read from the CLI, a lifecycle policy that keeps the ten newest tagged images, and pull access granted to a second AWS account.
- Store app secrets in AWS Secrets Manager and Parameter StoreYou will keep a database URL in Secrets Manager and a feature flag in Parameter Store, load both into a Node.js app at start-up with a cache, limit one IAM role to exactly those two values, and put an RDS password on a rotation schedule.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials