# Prompt-to-PR: Agregar carga de archivos a Cloudflare R2

> Procedimiento operativo estándar de extremo a extremo para conectar cargas presignadas de R2 en una aplicación Next.js o Cloudflare Workers — enlace de bucket, URLs presignadas y flujo de carga del cliente.

**Type:** Playbook  
**Tools:** Cursor, Claude Code, Codex, Windsurf  
**Stack:** Next.js, Cloudflare, TypeScript  
**Difficulty:** medium  
**Updated:** 2026-06-08

---

Agregar carga de archivos a R2 sin pasar datos binarios a través de tu servidor. El agente genera una URL presignada del lado del servidor; el PUT del navegador va directamente a R2.

## 1. Requisito

Los usuarios pueden cargar archivos (imágenes, PDFs, hasta 10 MB) mediante una interfaz de arrastrar y soltar. El servidor emite una URL PUT presignada; el navegador transmite el archivo directamente a Cloudflare R2. Se devuelve una URL de lectura pública después de la carga. Ningún archivo pasa a través del servidor de Next.js.

## 2. Primer prompt

```txt title="First Prompt"
Add Cloudflare R2 file upload to this Next.js 15 App Router project.

Requirements:
- Use presigned PUT URLs (not proxy upload). The Next.js route only issues
  the presigned URL; the browser uploads directly to R2.
- Install `@aws-sdk/client-s3` and `@aws-sdk/s3-request-presigner`
  (R2 is S3-compatible).
- Create `src/app/api/upload/presign/route.ts` (POST). Accept JSON body
  `{ filename: string; contentType: string; size: number }`. Validate:
  allowed MIME types (image/jpeg, image/png, image/webp, application/pdf),
  max size 10 MB. Return `{ uploadUrl, publicUrl, key }`.
- Read R2 credentials from env vars:
    R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY,
    R2_BUCKET_NAME, NEXT_PUBLIC_R2_PUBLIC_URL.
- Create `src/components/FileUpload.tsx` — a Client Component with a
  drag-and-drop zone. On file select: POST to /api/upload/presign, then
  PUT the file to the returned uploadUrl with the correct Content-Type header.
  Show progress, handle errors, and call an `onUpload(publicUrl)` callback.
- Do not store the file in any database table; that is the caller's
  responsibility via the onUpload callback.
```

## 3. Cambios de archivos esperados

```txt
package.json                                (@aws-sdk/client-s3, @aws-sdk/s3-request-presigner)
src/app/api/upload/presign/route.ts         (new — presign endpoint)
src/components/FileUpload.tsx               (new — drag-and-drop client component)
src/lib/r2.ts                               (new — S3Client singleton)
.env.local.example                          (R2_* vars)
```

## 4. Lista de verificación

- El endpoint de presign valida el tipo MIME y el tamaño antes de llamar a R2 — las cargas incorrectas se rechazan antes de cualquier llamada a AWS.
- El `S3Client` en `src/lib/r2.ts` usa `endpoint: https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com` y `region: "auto"`.
- La expiración de la URL presignada es corta (60–300 segundos); no un día completo.
- El `PUT` del navegador incluye el encabezado `Content-Type` que coincide con lo que se presignó — los desajustes causan 403.
- `NEXT_PUBLIC_R2_PUBLIC_URL` apunta al dominio público del bucket, no al endpoint de la API de R2.
- `FileUpload.tsx` comienza con `"use client"` — sin importaciones del servidor.
- No hay verificación de tamaño o tipo solo del lado del cliente — el servidor también debe validar.
- La clave usa un prefijo aleatorio (por ejemplo, `crypto.randomUUID()`) para evitar colisiones de nombres de archivo.

## 5. Comandos de prueba

```bash
# Start dev server
bun dev

# Test presign endpoint directly
curl -X POST http://localhost:3000/api/upload/presign \
  -H "Content-Type: application/json" \
  -d '{"filename":"test.png","contentType":"image/png","size":12345}' | jq .

# Confirm returned uploadUrl is an R2 presigned URL (contains X-Amz-Signature)
# Then PUT a real file to confirm end-to-end
curl -X PUT "<uploadUrl>" \
  -H "Content-Type: image/png" \
  --data-binary @test.png -v

# Fetch the public URL to verify the file is readable
curl -I "<publicUrl>"
```

## 6. Fallos comunes

- **403 en PUT** — el encabezado `Content-Type` en el PUT del navegador no coincide con el usado al presignar. Asegúrate de que ambos usen la misma cadena exacta.
- **`NoSuchBucket`** — nombre de bucket o ID de cuenta incorrectos. Vuelve a verificar `R2_BUCKET_NAME` en el panel de Cloudflare.
- **`InvalidAccessKeyId`** — el token de API de R2 necesita permiso de "Lectura y escritura de objetos", no solo "Lectura".
- **Error CORS en PUT directo** — la política CORS del bucket de R2 debe permitir `PUT` desde tu origen. Configúrala en el panel de Cloudflare en R2 → Configuración → CORS.
- **El agente usa `@aws-sdk/s3-presigned-post`** (para POST) en lugar de `getSignedUrl` para PUT — flujo diferente, se requiere código de cliente diferente.

## 7. Prompt de corrección

```txt title="Fix Prompt"
The browser PUT to R2 returns 403 SignatureDoesNotMatch.

The Content-Type passed to getSignedUrl must exactly match the Content-Type
header sent by the browser. Update the presign route to pass the contentType
from the request body into getSignedUrl, and update FileUpload.tsx to set
the Content-Type header on the PUT request to the same value.

Also confirm the S3Client endpoint is:
  https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com
not the generic AWS S3 endpoint.
```

## 8. Descripción del PR

```md title="PR description"
## Feature: Cloudflare R2 file upload via presigned URLs

- New POST `/api/upload/presign` validates MIME type and size, then returns
  a short-lived R2 presigned PUT URL
- Files upload directly from the browser to R2 — zero binary data through
  the Next.js server
- New `<FileUpload>` component: drag-and-drop, progress indicator, error state
- Random UUID key prefix prevents filename collisions

**Required env vars** (see `.env.local.example`):
`R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`,
`R2_BUCKET_NAME`, `NEXT_PUBLIC_R2_PUBLIC_URL`

**R2 bucket setup**: enable public access and add a CORS rule allowing PUT
from your app origin.
```