Set up and configure Cloudflare R2 object storage with S3-compatible API, bucket configuration, CORS, and authentication for your application.
Set up and configure Cloudflare R2 object storage with S3-compatible API, bucket configuration, CORS, and authentication.
Cloudflare R2 is S3-compatible object storage with zero egress bandwidth fees. This skill helps you:
Ask the user about their R2 setup needs:
**Via Cloudflare Dashboard:**
**Via Wrangler CLI:**
```bash
npx wrangler r2 bucket create <BUCKET_NAME> --location-hint <LOCATION>
```
Location hints: `wnam` (Western North America), `enam` (Eastern North America), `weur` (Western Europe), `eeur` (Eastern Europe), `apac` (Asia-Pacific)
**Option A: S3 API Access**
Generate R2 API token:
Set environment variables:
```bash
R2_ACCOUNT_ID=<your-account-id>
R2_ACCESS_KEY_ID=<your-access-key>
R2_SECRET_ACCESS_KEY=<your-secret-key>
R2_BUCKET_NAME=<your-bucket-name>
```
S3 endpoint format: `https://<ACCOUNT_ID>.r2.cloudflarestorage.com`
**Option B: Workers API**
Add R2 binding to `wrangler.toml`:
```toml
[[r2_buckets]]
binding = "MY_BUCKET"
bucket_name = "my-bucket"
```
**Option C: Public Bucket**
Enable public access via dashboard or API to expose bucket contents directly via HTTPS.
If accessing R2 from browser, configure CORS policy:
```json
[
{
"AllowedOrigins": ["https://example.com"],
"AllowedMethods": ["GET", "PUT", "POST", "DELETE"],
"AllowedHeaders": ["*"],
"ExposeHeaders": ["ETag"],
"MaxAgeSeconds": 3600
}
]
```
Apply via Wrangler:
```bash
npx wrangler r2 bucket cors put <BUCKET_NAME> --rules '<CORS_JSON>'
```
**Node.js (AWS SDK v3):**
```javascript
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
const s3 = new S3Client({
region: "auto",
endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
credentials: {
accessKeyId: process.env.R2_ACCESS_KEY_ID,
secretAccessKey: process.env.R2_SECRET_ACCESS_KEY,
},
});
await s3.send(new PutObjectCommand({
Bucket: process.env.R2_BUCKET_NAME,
Key: "path/to/file.jpg",
Body: fileBuffer,
}));
```
**Python (boto3):**
```python
import boto3
s3 = boto3.client(
"s3",
endpoint_url=f"https://{os.getenv('R2_ACCOUNT_ID')}.r2.cloudflarestorage.com",
aws_access_key_id=os.getenv("R2_ACCESS_KEY_ID"),
aws_secret_access_key=os.getenv("R2_SECRET_ACCESS_KEY"),
)
s3.upload_file("local-file.jpg", os.getenv("R2_BUCKET_NAME"), "path/to/file.jpg")
```
**Cloudflare Workers:**
```javascript
export default {
async fetch(request, env) {
const object = await env.MY_BUCKET.get("path/to/file.jpg");
return new Response(object.body);
},
};
```
For public buckets or custom domains:
Example: `avatars.example.com` → CNAME → `<bucket>.r2.cloudflarestorage.com`
Configure object lifecycle rules for automatic deletion or storage class transitions:
Test basic operations:
Provide the user with:
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/cloudflare-r2-setup/raw