npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@neuctra/r2-files-sdk

v1.0.2

Published

Simple SDK to upload, get, replace, list and delete files in Cloudflare R2 through the r2-files webhook

Readme

@neuctra/r2-files-sdk

Upload, get, replace, list and delete files in Cloudflare R2 with one function call each. No buckets, S3 signatures or multipart parsing to deal with.

  • Zero dependencies, fully typed, ESM + CommonJS
  • Works in Node 18+, Bun, Deno, Cloudflare Workers, Next.js and browsers
  • Large files are uploaded in parts automatically, and rate limits / 5xx errors are retried
 your app  ──(@neuctra/r2-files-sdk)──►  r2-files webhook (your Cloudflare Worker)  ──►  your R2 bucket

The SDK talks to the r2-files webhook, a small Cloudflare Worker that you deploy once to your own account. Your files stay in your own R2 bucket.

Setup

1. Deploy the webhook (once)

You need a free Cloudflare account and Node.js 22+ (for Wrangler; the SDK itself runs on Node 18+).

git clone https://github.com/Taha-Asif-313/cloudflare-r2-opensource.git
cd cloudflare-r2-opensource/webhook
npm install

npx wrangler login                       # opens the browser once
npx wrangler r2 bucket create my-files   # the bucket name used in wrangler.jsonc
npx wrangler secret put API_KEY          # paste a long random string (see below)
npm run deploy                           # prints https://r2-files-webhook.<you>.workers.dev

Generate a strong API key with:

node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

Settings such as public reads, a custom domain, size limits, allowed file types and CORS are covered in the webhook README.

2. Install the SDK

npm install @neuctra/r2-files-sdk
# or: pnpm add @neuctra/r2-files-sdk / yarn add @neuctra/r2-files-sdk / bun add @neuctra/r2-files-sdk

Put the worker URL and the API key in your app's server environment, e.g. R2_FILES_URL and R2_FILES_API_KEY.

Quick start

import { R2FilesClient } from "@neuctra/r2-files-sdk";

const files = new R2FilesClient({
  baseUrl: process.env.R2_FILES_URL!,       // https://r2-files-webhook.<you>.workers.dev
  apiKey: process.env.R2_FILES_API_KEY,     // the same value as the worker's API_KEY secret
});

const image = await files.upload(file, { folder: "avatars" });
console.log(image.url);    // https://.../files/avatars/3f2a...c1.png

await files.replace(image.key, newFile);    // same key, same URL
await files.delete(image.key);

API

upload(file, options?) → FileInfo

file can be a File, Blob, ArrayBuffer, Uint8Array / Node Buffer, or a string.

// Browser <input type="file">: name and type are picked up automatically
await files.upload(input.files[0], { folder: "avatars" });

// Your own key. Throws FILE_EXISTS if it's taken, unless overwrite: true
await files.upload(buffer, { folder: "avatars", key: "user-42.png", overwrite: true });

// Node: read from disk
import { readFile } from "node:fs/promises";
await files.upload(await readFile("./report.pdf"), { filename: "report.pdf", folder: "docs" });

// Node 20+: big files without loading them into memory
import { openAsBlob } from "node:fs";
await files.upload(await openAsBlob("./talk.mp4"), { filename: "talk.mp4", folder: "videos" });

// Text / JSON
await files.upload(JSON.stringify(data), { key: "exports/data.json", contentType: "application/json" });

// Custom metadata (strings only)
await files.upload(file, { metadata: { userId: "42", album: "summer" } });

| Option | Description | | ------------- | ----------- | | key | File name inside folder. Omit it to get a unique generated name. | | folder | Folder prefix, e.g. "avatars". | | filename | Original name, used for the extension and metadata.originalName. Taken from File.name when available. | | contentType | MIME type. Taken from Blob.type or guessed from the file name when omitted. | | overwrite | Allow overwriting an existing key. Default false. | | metadata | Record<string, string> stored with the file. R2 allows 8 KiB in total. |

When two uploads race for the same new key, exactly one succeeds. R2 checks this atomically.

replace(key, file, options?) → FileInfo

Replaces the content of an existing file. The key and URL don't change, and the existing metadata is kept unless you pass new metadata. Throws NOT_FOUND if the file doesn't exist, and PRECONDITION_FAILED if it changed mid-replace (just retry).

await files.replace("avatars/user-42.png", newPhoto);

get(key) → Blob

const blob = await files.get("docs/report.pdf");
const text = await (await files.get("notes.txt")).text();
img.src = URL.createObjectURL(await files.get("avatars/user-42.png")); // browser

getUrl(key, { download? }) → string

Builds the URL without making a request, which is ideal for <img src>. Reading without an API key needs PUBLIC_READ=true on the server.

files.getUrl("avatars/user-42.png");                     // display
files.getUrl("docs/report.pdf", { download: true });     // force download

getInfo(key) → FileInfo and exists(key) → boolean

const { size, contentType, metadata } = await files.getInfo("docs/report.pdf");
if (await files.exists("avatars/user-42.png")) { /* ... */ }

delete(key) and deleteMany(keys)

await files.delete("avatars/user-42.png");              // throws NOT_FOUND if missing
await files.deleteMany(["a.png", "b.png", "c.png"]);    // any count, batched for you

list(options?) → { files, folders, truncated, cursor } and listAll(options?)

const page = await files.list({ prefix: "avatars/", limit: 50 });
const next = await files.list({ prefix: "avatars/", cursor: page.cursor! });

// Only direct children; sub-folders come back in `folders`
const { files: rootFiles, folders } = await files.list({ recursive: false });

// Every file, across all pages
for await (const file of files.listAll({ prefix: "avatars/" })) console.log(file.key);

// Delete a whole folder
const keys = [];
for await (const f of files.listAll({ prefix: "tmp/" })) keys.push(f.key);
await files.deleteMany(keys);

Large files

A single request to a Worker is capped by your Cloudflare plan (100 MB on Free and Pro). Files over multipartThreshold (50 MiB by default) are therefore sent with R2's multipart API:

  • They're split into equal parts of partSize (10 MiB by default; R2 requires at least 5 MiB).
  • Up to concurrency parts upload in parallel.
  • Everything is reassembled in R2.

If any part fails, the upload is aborted. You call upload() and replace() exactly the same way; the switch happens automatically. The server's MAX_UPLOAD_MB still applies, so raise it to allow big files.

const files = new R2FilesClient({ baseUrl, apiKey, partSize: 20 * 1024 * 1024, concurrency: 6 });
await files.upload(await openAsBlob("./backup.zip"), { folder: "backups" });

FileInfo

{
  key: string;          // "avatars/user-42.png"
  url: string;          // link to read the file
  size: number;         // bytes
  contentType: string;
  etag: string;
  uploadedAt: string;   // ISO date
  metadata: Record<string, string>;
}

Errors

Every failure throws an R2FilesError with an HTTP status and a code:

import { R2FilesError } from "@neuctra/r2-files-sdk";

try {
  await files.upload(file, { key: "logo.png" });
} catch (err) {
  if (err instanceof R2FilesError && err.code === "FILE_EXISTS") {
    await files.replace("logo.png", file);
  } else throw err;
}

| Code | Status | When | | ---- | ------ | ---- | | NOT_FOUND | 404 | The file doesn't exist | | FILE_EXISTS | 409 | Upload to a taken key without overwrite | | OBJECT_LOCKED | 409 | The file is protected by a bucket lock rule | | PRECONDITION_FAILED | 412 | The file changed or was deleted during replace(); retry | | UNAUTHORIZED | 401 | Missing or wrong apiKey | | FILE_TOO_LARGE | 413 | Over the server's MAX_UPLOAD_MB | | TYPE_NOT_ALLOWED | 415 | Blocked by the server's ALLOWED_TYPES | | INVALID_KEY | 400 | Empty key, .. segments, or over 1024 bytes | | METADATA_TOO_LARGE | 400 | Custom metadata over R2's 8 KiB limit | | RATE_LIMITED | 429 | More than 1 write per second to the same key (retried automatically first) | | NETWORK_ERROR | 0 | The server couldn't be reached |

Rate limits (429) and 503s are retried for every call. Other 5xx and network errors are only retried for calls that are safe to repeat (reads, replace, deletes and parts), not for upload(), so a retry can't create a duplicate file. Set retries: 0 to turn this off.

Keep the API key on the server

The API key can delete every file, so never ship it to the browser. Upload from your backend instead. For example, a Next.js route handler:

// app/api/upload/route.ts
import { R2FilesClient } from "@neuctra/r2-files-sdk";

const files = new R2FilesClient({ baseUrl: process.env.R2_FILES_URL!, apiKey: process.env.R2_FILES_API_KEY });

export async function POST(req: Request) {
  // ...check the user is logged in...
  const form = await req.formData();
  const file = form.get("file") as File;
  const info = await files.upload(file, { folder: "avatars" });
  return Response.json({ url: info.url });
}

Reading public files from the browser needs no key: new R2FilesClient({ baseUrl }).getUrl(key).

Client options

| Option | Description | | ----------- | ----------- | | baseUrl | Required. Your webhook worker URL. | | apiKey | The server's API_KEY. Not needed for reading public files. | | publicUrl | Use this base (e.g. an R2 custom domain) for getUrl() instead of ${baseUrl}/files. | | fetch | Custom fetch implementation. | | headers | Extra headers sent with every request. | | multipartThreshold | Files larger than this (bytes) are uploaded in parts. Default 50 MiB. | | partSize | Part size in bytes. Default 10 MiB, minimum 5 MiB, and it must be under your plan's request limit. It grows automatically to stay within 10,000 parts. | | concurrency | Parts uploaded in parallel. Default 4. | | retries | Retry attempts with exponential backoff. Default 2. |

Using an AI coding assistant?

Install @neuctra/r2-files-mcp so Claude Code, Cursor, VS Code Copilot and others look up this SDK's real API instead of guessing:

claude mcp add r2-files -- npx -y @neuctra/r2-files-mcp   # Claude Code

Setup for other clients is in the MCP README.

Development

git clone https://github.com/Taha-Asif-313/cloudflare-r2-opensource.git
cd cloudflare-r2-opensource/sdk
npm install
npm run typecheck
npm run build          # dist/ with ESM, CJS and .d.ts
npm publish            # runs typecheck + build first

publishConfig.access is set to public in package.json, so the scoped package publishes publicly. Bump version before each publish.

License

MIT