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.
CursorClaude CodeCodexWindsurf Next.jsCloudflareTypeScript
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
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
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
S3Clientensrc/lib/r2.tsusaendpoint: https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.comyregion: "auto". - La expiración de la URL presignada es corta (60–300 segundos); no un día completo.
- El
PUTdel navegador incluye el encabezadoContent-Typeque coincide con lo que se presignó — los desajustes causan 403. NEXT_PUBLIC_R2_PUBLIC_URLapunta al dominio público del bucket, no al endpoint de la API de R2.FileUpload.tsxcomienza 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
# Start dev serverbun dev
# Test presign endpoint directlycurl -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-endcurl -X PUT "<uploadUrl>" \ -H "Content-Type: image/png" \ --data-binary @test.png -v
# Fetch the public URL to verify the file is readablecurl -I "<publicUrl>"6. Fallos comunes
- 403 en PUT — el encabezado
Content-Typeen 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 verificarR2_BUCKET_NAMEen 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
PUTdesde 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 degetSignedUrlpara PUT — flujo diferente, se requiere código de cliente diferente.
7. Prompt de corrección
The browser PUT to R2 returns 403 SignatureDoesNotMatch.
The Content-Type passed to getSignedUrl must exactly match the Content-Typeheader sent by the browser. Update the presign route to pass the contentTypefrom the request body into getSignedUrl, and update FileUpload.tsx to setthe Content-Type header on the PUT request to the same value.
Also confirm the S3Client endpoint is: https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.comnot the generic AWS S3 endpoint.8. Descripción del PR
## 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 PUTfrom your app origin.