# Cloudflare R2 Quick Start

A step-by-step guide to get your uploads working with Cloudflare R2 in under 10 minutes.

## ⚡ Quick Setup (3 Steps)

### 1️⃣ Create R2 Bucket

1. Go to [Cloudflare Dashboard](https://dash.cloudflare.com/) → **R2**
2. Click **"Create bucket"** → Name it `magasinetkbh-uploads`
3. Location: `Automatic` → **Create**

### 2️⃣ Get API Credentials

1. In R2, click **"Manage R2 API Tokens"**
2. **Create API Token** with these settings:
   - Name: `magasinetkbh-upload`
   - Permissions: **Object Read & Write**
   - Bucket: `magasinetkbh-uploads` (or all buckets)
3. **Save these values** (you'll need them):
   - ✅ Access Key ID
   - ✅ Secret Access Key
   - ✅ Account ID (shown at top of R2 page)

### 3️⃣ Enable Public Access

1. Go to your bucket → **Settings** tab
2. Under **Public access**, click **"Allow Access"**
3. Click **"Connect R2.dev subdomain"**
4. **Copy the URL** shown (e.g., `https://pub-abc123.r2.dev`)

## 🔧 Configuration

Update your `.env.local`:

```bash
# Replace these values with your actual R2 credentials
S3_ENDPOINT=https://YOUR_ACCOUNT_ID.r2.cloudflarestorage.com
S3_REGION=auto
S3_ACCESS_KEY_ID=YOUR_R2_ACCESS_KEY_ID
S3_SECRET_ACCESS_KEY=YOUR_R2_SECRET_ACCESS_KEY
S3_BUCKET_NAME=magasinetkbh-uploads
S3_PUBLIC_URL=https://pub-YOUR_R2_SUBDOMAIN.r2.dev
```

### Example Configuration

```bash
# Real example (with fake credentials)
S3_ENDPOINT=https://1234567890abcdef.r2.cloudflarestorage.com
S3_REGION=auto
S3_ACCESS_KEY_ID=a1b2c3d4e5f6g7h8i9j0
S3_SECRET_ACCESS_KEY=abcdefghijklmnopqrstuvwxyz1234567890ABCD
S3_BUCKET_NAME=magasinetkbh-uploads
S3_PUBLIC_URL=https://pub-xyz789abc456.r2.dev
```

## ✅ Test Your Setup

1. **Restart your dev server**:
   ```bash
   npm run dev
   ```

2. **Try uploading a file** in your app

3. **Verify in Cloudflare**:
   - Go to R2 → Your bucket
   - You should see the uploaded file

4. **Test public access**:
   - Copy the file's public URL from your app
   - Open it in a new browser tab
   - If you see the file → ✅ Success!

## 🔍 Troubleshooting

### ❌ "Access Denied" Error

**Check:**
- API token has **Object Read & Write** permission
- Token is for the correct bucket
- Credentials are copied correctly (no extra spaces)

**Fix:**
```bash
# Verify your credentials in .env.local
# Make sure there are no quotes around the values
S3_ACCESS_KEY_ID=abc123  # ✅ Good
S3_ACCESS_KEY_ID="abc123"  # ❌ Bad
```

### ❌ File Uploads but Can't Access

**Check:**
- Public access is enabled on bucket
- R2.dev subdomain is connected
- `S3_PUBLIC_URL` matches your R2.dev URL exactly

**Fix:**
1. Go to bucket → Settings → Public access
2. Ensure "Allow Access" is enabled
3. Copy the exact R2.dev URL
4. Update `S3_PUBLIC_URL` in `.env.local`

### ❌ "Invalid Endpoint" Error

**Check:**
- Endpoint includes your Account ID
- Endpoint uses HTTPS (not HTTP)
- No trailing slash

**Fix:**
```bash
# Format should be:
S3_ENDPOINT=https://<account-id>.r2.cloudflarestorage.com

# Common mistakes:
S3_ENDPOINT=http://...  # ❌ Must be HTTPS
S3_ENDPOINT=https://.../ # ❌ No trailing slash
```

### ❌ CORS Errors

**If uploading from browser:**

1. Go to bucket → Settings → CORS policy
2. Add this configuration:

```json
[
  {
    "AllowedOrigins": [
      "http://localhost:3000",
      "https://yourdomain.com"
    ],
    "AllowedMethods": [
      "GET",
      "PUT",
      "POST",
      "DELETE"
    ],
    "AllowedHeaders": ["*"],
    "ExposeHeaders": ["ETag"],
    "MaxAgeSeconds": 3000
  }
]
```

## 🎯 Where to Find Things

### Account ID
- Dashboard → R2 → Top of page
- Or in the R2 URL: `dash.cloudflare.com/<account-id>/r2`

### R2.dev Public URL
- R2 → Your bucket → Settings → Public access
- Will look like: `https://pub-xxxxx.r2.dev`

### API Token
- R2 → Manage R2 API Tokens
- If lost, create a new one (can't view old tokens)

## 💰 Costs

Cloudflare R2 is **extremely cheap**:

- Storage: $0.015/GB/month
- Reads: $0.36 per million
- Writes: $4.50 per million
- **Egress: FREE** (this is huge!)

**Example**: 10GB storage + 100k uploads + 1M downloads = **~$1.60/month**

## 🚀 Next Steps

### Production Best Practices

1. **Use Custom Domain** (optional but recommended):
   ```bash
   # Instead of R2.dev subdomain:
   S3_PUBLIC_URL=https://cdn.yourdomain.com
   ```
   - Go to bucket → Settings → Custom Domains
   - Add your domain and update DNS

2. **Separate Dev and Prod Buckets**:
   ```bash
   # Development
   S3_BUCKET_NAME=magasinetkbh-uploads-dev
   
   # Production
   S3_BUCKET_NAME=magasinetkbh-uploads-prod
   ```

3. **Set Up Lifecycle Rules** (auto-delete old files):
   - Bucket → Settings → Lifecycle rules
   - Example: Delete files older than 90 days

4. **Monitor Usage**:
   - R2 dashboard shows storage and operation costs
   - Set up billing alerts in Cloudflare

## 📚 Full Documentation

For detailed information, see:
- [Full R2 Setup Guide](./cloudflare-r2.md)
- [Cloudflare R2 Docs](https://developers.cloudflare.com/r2/)

## ✨ Benefits Over MinIO

| Feature | MinIO (Dev) | Cloudflare R2 (Prod) |
|---------|-------------|----------------------|
| Setup | Docker required | Cloud-based (instant) |
| Maintenance | Manual updates | Fully managed |
| Scaling | Limited to server | Automatic & unlimited |
| Egress Costs | N/A | **FREE** ✨ |
| CDN | Need separate setup | Built-in global network |
| Reliability | Single server | 99.99% SLA |

## 🤝 Need Help?

If you're still having issues:

1. Check the [Troubleshooting](#-troubleshooting) section
2. Verify all environment variables are set correctly
3. Check Cloudflare R2 status page
4. Review the [full documentation](./cloudflare-r2.md)

---

**Your files should now upload to Cloudflare R2! 🎉**

Test by uploading a file through your app and checking your R2 bucket in the Cloudflare dashboard.

