# Prompt-to-PR: Adicionar Upload de Arquivos para Cloudflare R2

> SOP completa para integrar uploads R2 com URLs pré-assinadas em um app Next.js ou Cloudflare Workers — binding de bucket, URLs pré-assinadas e fluxo de upload do cliente.

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

---

Adicione upload de arquivos para o R2 sem passar dados binários pelo seu servidor. O agente gera uma URL pré-assinada no servidor; o navegador faz o PUT diretamente para o R2.

## 1. Requisito

Usuários podem fazer upload de arquivos (imagens, PDFs, até 10 MB) via interface de arrastar e soltar. O servidor emite uma URL pré-assinada de PUT; o navegador envia o arquivo diretamente para o Cloudflare R2. Uma URL de leitura pública é retornada após o upload. Nenhum arquivo passa pelo servidor Next.js.

## 2. Primeiro 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. Mudanças Esperadas nos Arquivos

```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 Verificação

- O endpoint de pré-assinatura valida o tipo MIME e o tamanho antes de chamar o R2 — uploads ruins são rejeitados antes de qualquer chamada AWS.
- O `S3Client` em `src/lib/r2.ts` usa `endpoint: https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com` e `region: "auto"`.
- A expiração da URL pré-assinada é curta (60–300 segundos); não um dia inteiro.
- O `PUT` do navegador inclui o cabeçalho `Content-Type` que corresponde ao usado na pré-assinatura — incompatibilidades causam 403.
- `NEXT_PUBLIC_R2_PUBLIC_URL` aponta para o domínio público do bucket, não para o endpoint da API do R2.
- `FileUpload.tsx` começa com `"use client"` — sem imports de servidor.
- Não há verificação de tamanho ou tipo apenas no lado do cliente — o servidor também deve validar.
- A chave usa um prefixo aleatório (ex.: `crypto.randomUUID()`) para evitar colisões de nomes de arquivos.

## 5. Comandos de Teste

```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. Falhas Comuns

- **403 no PUT** — O cabeçalho `Content-Type` no PUT do navegador não corresponde ao usado na pré-assinatura. Certifique-se de que ambos usam a mesma string exata.
- **`NoSuchBucket`** — Nome do bucket ou ID de conta errados. Verifique novamente `R2_BUCKET_NAME` no painel do Cloudflare.
- **`InvalidAccessKeyId`** — O token da API do R2 precisa da permissão "Object Read & Write", não apenas "Read".
- **Erro de CORS no PUT direto** — A política de CORS do bucket R2 deve permitir `PUT` da sua origem. Defina-a no painel do Cloudflare em R2 → Configurações → CORS.
- **Agente usa `@aws-sdk/s3-presigned-post`** (para POST) em vez de `getSignedUrl` para PUT — fluxo diferente, código do cliente diferente necessário.

## 7. Prompt de Correção

```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. Descrição do 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.
```