{
  "id": "add-cloudflare-r2-file-upload",
  "type": "prompts",
  "category": "prompts",
  "locale": "en",
  "url": "/prompts/add-cloudflare-r2-file-upload",
  "title": "Prompt to Add Cloudflare R2 File Upload",
  "description": "Copy-paste AI prompt to add Cloudflare R2 presigned upload URLs to a Next.js App Router project with server-side validation.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "Cloudflare",
    "TypeScript"
  ],
  "tags": [
    "cloudflare",
    "nextjs",
    "typescript",
    "build"
  ],
  "difficulty": "medium",
  "updated": "2026-06-08",
  "markdown": "Give this prompt to your agent to implement direct-to-R2 file uploads using presigned\nURLs — keeping secrets server-side and avoiding the common mistake of routing file\nbytes through your Next.js server.\n\n## Main Prompt\n\n```txt title=\"Main Prompt\"\nYou are working in a Next.js App Router project using TypeScript.\n\nTask: add Cloudflare R2 file upload via presigned PUT URLs.\n\nRequirements:\n- Install `@aws-sdk/client-s3` and `@aws-sdk/s3-request-presigner` (R2 is S3-compatible).\n- Create a Server Action in `src/lib/actions/get-upload-url.ts` that:\n  - Accepts `{ filename: string; contentType: string; sizeBytes: number }`.\n  - Validates: `sizeBytes` must be <= 10_485_760 (10 MB); `contentType` must start with `image/`.\n  - Uses `PutObjectCommand` + `getSignedUrl` to generate a 60-second presigned URL.\n  - Returns `{ uploadUrl: string; publicUrl: string; key: string }`.\n- Store credentials in `.env`: `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`,\n  `R2_BUCKET_NAME`, `R2_PUBLIC_URL`.\n- Create a client component `src/components/FileUploader.tsx` that:\n  - Renders a file `<input accept=\"image/*\" />`.\n  - On change: calls the Server Action to get the presigned URL, then does a `fetch` PUT directly\n    to R2, then shows the `publicUrl` as a preview.\n  - Shows upload progress via `XMLHttpRequest` `progress` events (not fetch, which lacks progress).\n- Do not add any other dependencies. Do not modify `next.config.ts` unless required for image domains.\n\nStop and list all planned file changes before writing any code.\n```\n\n## Implementation Notes\n\n- R2 uses the S3 SDK with `endpoint: https://<accountId>.r2.cloudflarestorage.com` and\n  `region: 'auto'`. Forgetting `region: 'auto'` causes a signature error.\n- Presigned URLs are generated server-side; the client never sees `R2_SECRET_ACCESS_KEY`.\n- For public bucket access, set the R2 bucket's \"Public access\" toggle in the Cloudflare dashboard\n  and supply the resulting `r2.dev` URL as `R2_PUBLIC_URL`.\n\n## Expected File Changes\n\n```txt\nsrc/lib/actions/get-upload-url.ts      (new)\nsrc/lib/r2.ts                          (new — S3Client singleton)\nsrc/components/FileUploader.tsx        (new — Client Component)\n.env.example                           (edited)\npackage.json                           (edited)\nnext.config.ts                         (edited — add r2.dev to images.remotePatterns)\n```\n\n## Acceptance Criteria\n\n- A file selected in `FileUploader` triggers a presigned URL fetch, then uploads directly to R2.\n- Files larger than 10 MB are rejected before any network request.\n- Non-image MIME types are rejected server-side and return a 400-equivalent error.\n- The public URL preview renders the uploaded image after upload completes.\n\n## Test Commands\n\n```bash\nbun run typecheck\nbun run dev\n# upload a PNG < 10 MB via the component and confirm it appears in R2 bucket\n# attempt a 15 MB file and confirm rejection\n# attempt a .pdf and confirm rejection\n```\n\n## Common AI Mistakes\n\n- Setting `region: 'us-east-1'` instead of `'auto'`, causing `SignatureDoesNotMatch` errors.\n- Routing the file bytes through the Next.js Server Action instead of fetching directly to R2.\n- Forgetting to call `'use server'` at the top of the actions file.\n- Using `fetch` for the upload and losing progress events.\n\n## Fix Prompt\n\n```txt title=\"Fix Prompt\"\nThe upload fails with `SignatureDoesNotMatch` or the file routes through the server.\nFix in order:\n1. In `src/lib/r2.ts`, set `region: 'auto'` and `endpoint: https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com`.\n2. In `FileUploader.tsx`, use `XMLHttpRequest` with a `progress` event to PUT directly to the\n   presigned URL — not fetch, and not a Server Action for the actual upload bytes.\nShow corrected diff only.\n```"
}