Cloudflare R2 logo

Cloudflare R2

Community
einverne
cloudflare-r2

Guide for implementing Cloudflare R2 - S3-compatible object storage with zero egress fees. Use when implementing file storage, uploads/downloads, data migration to/from R2, configuring buckets, integrating with Workers, or working with R2 APIs and SDKs.

Overview

Publishereinverne
Repositorydotfiles
Skill namecloudflare-r2
Stars
121
Forks
24
Bundled files
4
LicenseGPL-3.0
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 4 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by einverne on GitHub. Read the source before you install it.

Installation

Install the Cloudflare R2 AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/einverne/dotfiles.git /tmp/dotfiles
mkdir -p .claude/skills
cp -r /tmp/dotfiles/claude/skills/cloudflare-r2 .claude/skills/cloudflare-r2
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Cloudflare R2 in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Cloudflare R2 on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Cloudflare R2 is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Cloudflare R2

S3-compatible object storage with zero egress bandwidth fees. Built on Cloudflare's global network for high durability (11 nines) and strong consistency.

When to Use This Skill

  • Implementing object storage for applications
  • Migrating from AWS S3 or other storage providers
  • Setting up file uploads/downloads
  • Configuring public or private buckets
  • Integrating R2 with Cloudflare Workers
  • Using R2 with S3-compatible tools and SDKs
  • Configuring CORS, lifecycles, or event notifications
  • Optimizing storage costs with zero egress fees

Prerequisites

Required:

  • Cloudflare account with R2 purchased
  • Account ID from Cloudflare dashboard

For API access:

  • R2 Access Keys (Access Key ID + Secret Access Key)
  • Generate from: Cloudflare Dashboard → R2 → Manage R2 API Tokens

For Wrangler CLI:

bash
npm install -g wrangler
wrangler login

Core Concepts

Architecture

  • S3-compatible API - works with AWS SDKs and tools
  • Workers API - native Cloudflare Workers integration
  • Global network - strong consistency across all regions
  • Zero egress fees - no bandwidth charges for data retrieval

Storage Classes

  • Standard - default, optimized for frequent access
  • Infrequent Access - lower storage cost, retrieval fees apply, 30-day minimum

Access Methods

  1. R2 Workers Binding - serverless integration (recommended for new apps)
  2. S3 API - compatibility with existing tools
  3. Public buckets - direct HTTP access via custom domains or r2.dev
  4. Presigned URLs - temporary access without credentials

Quick Start

1. Create Bucket

Wrangler:

bash
wrangler r2 bucket create my-bucket

With location hint:

bash
wrangler r2 bucket create my-bucket --location=wnam

Locations: wnam (West NA), enam (East NA), weur (West EU), eeur (East EU), apac (Asia Pacific)

2. Upload Object

Wrangler:

bash
wrangler r2 object put my-bucket/file.txt --file=./local-file.txt

Workers API:

javascript
await env.MY_BUCKET.put('file.txt', fileContents, {
  httpMetadata: {
    contentType: 'text/plain',
  },
});

3. Download Object

Wrangler:

bash
wrangler r2 object get my-bucket/file.txt --file=./downloaded.txt

Workers API:

javascript
const object = await env.MY_BUCKET.get('file.txt');
const contents = await object.text();

Workers Integration

Binding Configuration

wrangler.toml:

toml
[[r2_buckets]]
binding = "MY_BUCKET"
bucket_name = "my-bucket"
preview_bucket_name = "my-bucket-preview"

Common Operations

Upload with metadata:

javascript
await env.MY_BUCKET.put('user-uploads/photo.jpg', imageData, {
  httpMetadata: {
    contentType: 'image/jpeg',
    cacheControl: 'public, max-age=31536000',
  },
  customMetadata: {
    uploadedBy: userId,
    uploadDate: new Date().toISOString(),
  },
});

Download with streaming:

javascript
const object = await env.MY_BUCKET.get('large-file.mp4');
if (object === null) {
  return new Response('Not found', { status: 404 });
}

return new Response(object.body, {
  headers: {
    'Content-Type': object.httpMetadata.contentType,
    'ETag': object.etag,
  },
});

List objects:

javascript
const listed = await env.MY_BUCKET.list({
  prefix: 'user-uploads/',
  limit: 100,
});

for (const object of listed.objects) {
  console.log(object.key, object.size);
}

Delete object:

javascript
await env.MY_BUCKET.delete('old-file.txt');

Check if object exists:

javascript
const object = await env.MY_BUCKET.head('file.txt');
if (object) {
  console.log('Exists:', object.size, 'bytes');
}

S3 SDK Integration

AWS CLI

Configure:

bash
aws configure
# Access Key ID: <your-key-id>
# Secret Access Key: <your-secret>
# Region: auto

Operations:

bash
# List buckets
aws s3api list-buckets --endpoint-url https://<accountid>.r2.cloudflarestorage.com

# Upload file
aws s3 cp file.txt s3://my-bucket/ --endpoint-url https://<accountid>.r2.cloudflarestorage.com

# Generate presigned URL (expires in 1 hour)
aws s3 presign s3://my-bucket/file.txt --endpoint-url https://<accountid>.r2.cloudflarestorage.com --expires-in 3600

JavaScript (AWS SDK v3)

javascript
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";

const s3 = new S3Client({
  region: "auto",
  endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
  credentials: {
    accessKeyId: process.env.R2_ACCESS_KEY_ID,
    secretAccessKey: process.env.R2_SECRET_ACCESS_KEY,
  },
});

await s3.send(new PutObjectCommand({
  Bucket: "my-bucket",
  Key: "file.txt",
  Body: fileContents,
}));

Python (Boto3)

python
import boto3

s3 = boto3.client(
    service_name="s3",
    endpoint_url=f'https://{account_id}.r2.cloudflarestorage.com',
    aws_access_key_id=access_key_id,
    aws_secret_access_key=secret_access_key,
    region_name="auto",
)

# Upload file
s3.upload_fileobj(file_obj, 'my-bucket', 'file.txt')

# Download file
s3.download_file('my-bucket', 'file.txt', './local-file.txt')

Rclone (Large Files)

Configure:

bash
rclone config
# Select: Amazon S3 → Cloudflare R2
# Enter credentials and endpoint

Upload with multipart optimization:

bash
# For large files (>100MB)
rclone copy large-video.mp4 r2:my-bucket/ \
  --s3-upload-cutoff=100M \
  --s3-chunk-size=100M

Public Buckets

Enable Public Access

Wrangler:

bash
wrangler r2 bucket create my-public-bucket
# Then enable in dashboard: R2 → Bucket → Settings → Public Access

Access URLs

r2.dev (development only, rate-limited):

https://pub-<hash>.r2.dev/file.txt

Custom domain (recommended for production):

  1. Dashboard → R2 → Bucket → Settings → Public Access
  2. Add custom domain
  3. Cloudflare handles DNS/TLS automatically

CORS Configuration

Required for:

  • Browser-based uploads
  • Cross-origin API calls
  • Presigned URL usage from web apps

Wrangler:

bash
wrangler r2 bucket cors put my-bucket --rules '[
  {
    "AllowedOrigins": ["https://example.com"],
    "AllowedMethods": ["GET", "PUT", "POST"],
    "AllowedHeaders": ["*"],
    "ExposeHeaders": ["ETag"],
    "MaxAgeSeconds": 3600
  }
]'

Important: Origins must match exactly (no trailing slash).

Multipart Uploads

For files >100MB or parallel uploads:

Workers API:

javascript
const multipart = await env.MY_BUCKET.createMultipartUpload('large-file.mp4');

// Upload parts (5MiB - 5GiB each, max 10,000 parts)
const part1 = await multipart.uploadPart(1, chunk1);
const part2 = await multipart.uploadPart(2, chunk2);

// Complete upload
const object = await multipart.complete([part1, part2]);

Constraints:

  • Part size: 5MiB - 5GiB
  • Max parts: 10,000
  • Max object size: 5TB
  • Incomplete uploads auto-abort after 7 days (configurable via lifecycle)

Data Migration

Sippy (Incremental, On-Demand)

Best for: Gradual migration, avoiding upfront egress fees

bash
# Enable for bucket
wrangler r2 bucket sippy enable my-bucket \
  --provider=aws \
  --bucket=source-bucket \
  --region=us-east-1 \
  --access-key-id=$AWS_KEY \
  --secret-access-key=$AWS_SECRET

Objects migrate when first requested. Subsequent requests served from R2.

Super Slurper (Bulk, One-Time)

Best for: Complete migration, known object list

  1. Dashboard → R2 → Data Migration → Super Slurper
  2. Select source provider (AWS, GCS, Azure)
  3. Enter credentials and bucket name
  4. Start migration

Lifecycle Rules

Auto-delete or transition storage classes:

Wrangler:

bash
wrangler r2 bucket lifecycle put my-bucket --rules '[
  {
    "action": {"type": "AbortIncompleteMultipartUpload"},
    "filter": {},
    "abortIncompleteMultipartUploadDays": 7
  },
  {
    "action": {"type": "Transition", "storageClass": "InfrequentAccess"},
    "filter": {"prefix": "archives/"},
    "daysFromCreation": 90
  }
]'

Event Notifications

Trigger Workers on bucket events:

Wrangler:

bash
wrangler r2 bucket notification create my-bucket \
  --queue=my-queue \
  --event-type=object-create

Supported events:

  • object-create - new uploads
  • object-delete - deletions

Message format:

json
{
  "account": "account-id",
  "bucket": "my-bucket",
  "object": {"key": "file.txt", "size": 1024, "etag": "..."},
  "action": "PutObject",
  "eventTime": "2024-01-15T12:00:00Z"
}

Best Practices

Performance

  • Use Cloudflare Cache with custom domains for frequently accessed objects
  • Multipart uploads for files >100MB (faster, more reliable)
  • Rclone for batch operations (concurrent transfers)
  • Location hints match user geography

Security

  • Never commit Access Keys to version control
  • Use environment variables for credentials
  • Bucket-scoped tokens for least privilege
  • Presigned URLs for temporary access
  • Enable Cloudflare Access for additional protection

Cost Optimization

  • Infrequent Access storage for archives (30+ day retention)
  • Lifecycle rules to auto-transition or delete
  • Larger multipart chunks = fewer Class A operations
  • Monitor usage via dashboard analytics

Naming

  • Bucket names: lowercase, hyphens, 3-63 chars
  • Avoid sequential prefixes for better performance (e.g., use hashed prefixes)
  • No dots in bucket names if using custom domains with TLS

Limits

  • Buckets per account: 1,000
  • Object size: 5TB max
  • Bucket name: 3-63 characters
  • Lifecycle rules: 1,000 per bucket
  • Event notification rules: 100 per bucket
  • r2.dev rate limit: 1,000 req/min (use custom domains for production)

Troubleshooting

401 Unauthorized:

  • Verify Access Keys are correct
  • Check endpoint URL includes account ID
  • Ensure region is "auto" for most operations

403 Forbidden:

  • Check bucket permissions and token scopes
  • Verify CORS configuration for browser requests
  • Confirm bucket exists and name is correct

404 Not Found:

  • Object key case-sensitive
  • Check bucket name spelling
  • Verify object was uploaded successfully

Presigned URLs not working:

  • Verify CORS configuration
  • Check URL expiry time
  • Ensure origin matches CORS rules exactly

Multipart upload failures:

  • Part size must be 5MiB - 5GiB
  • Max 10,000 parts per upload
  • Complete upload within 7 days (or configure lifecycle)

Reference Files

For detailed documentation, see:

  • references/api-reference.md - Complete API endpoint documentation
  • references/sdk-examples.md - SDK examples for all languages
  • references/workers-patterns.md - Advanced Workers integration patterns
  • references/pricing-guide.md - Detailed pricing and cost optimization

Additional Resources

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Cloudflare R2 AI skill do?

Guide for implementing Cloudflare R2 - S3-compatible object storage with zero egress fees. Use when implementing file storage, uploads/downloads, data migration to/from R2, configuring buckets, integrating with Workers, or working with R2 APIs and SDKs.

Why use Cloudflare R2 on TypingMind?

Because you install it once and use it with any model. Cloudflare R2 is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Cloudflare R2 in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/einverne/dotfiles/tree/master/claude/skills/cloudflare-r2. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Cloudflare R2?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Cloudflare R2?

As many as you like. As long as a model supports skills, you can use Cloudflare R2 with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Cloudflare R2 AI skill free?

Yes. It is published on GitHub by einverne under the GPL-3.0 license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇