okayus/okayus-skills/cloudflare-r2-private-image-upload
Claude Code and agent skill by okayus/okayus-skills
- community
Checking that the SKILL.md file is still in the repository.
Store user-uploaded photos in a PRIVATE Cloudflare R2 bucket and serve them through the Worker only after session + space-membership authorization, with client-side downscaling (EXIF/GPS stripped) before upload. Use when a Workers + Hono + D1 app needs image upload where photos must stay private to the family/space (no public bucket, no r2.dev URL), when an uploaded image returns 404 after switching between `vite dev` and `wrangler dev`, when `wrangler deploy` fails with `Authentication error` (code 10000) on `/r2/buckets` after adding `r2_buckets`, or when an iPhone HEIC photo won't display on Android. Covers the decision matrix with pricing verified 2026-08 (R2 free tier, Images 5,000 free transformations and the Free-plan 9422 error), the no-extension key scheme `<prefix>/<spaceId>/<parentId>/<id>`, magic-bytes validation, the authorize-before-R2 serve route with conditional GET, delete ordering, thumbnails (client variants vs Images binding cached into R2), e2e, and the no-PITR backup decision.
Install
npx vskill@latest install okayus/okayus-skills/cloudflare-r2-private-image-uploadSKILL.md
The same SKILL.md was published earlier as okayus/okayus-skills/cloudflare-r2-private-image-upload.
Private R2 image upload, served through the Worker
Provenance: extracted from nyalog (ADR-006 "medical images on R2 + Worker proxy", PRs #40–#42 — the attachment routes have run in production since 2026-05). Pricing and limits were re-verified against developers.cloudflare.com on 2026-08-22; nyalog's ADR quoted a "25 GB / 5K writes" R2 free tier that was wrong — the real numbers are in the table below. This skill was written ahead of its second consumer (matatabetai meal photos); that implementation landed 2026-09-01 (matatabetai PR #27, local dev + e2e — prod deploy pending R2 bucket creation) and confirmed several claims below.
Why this shape: a family photo is private data. The moment a photo has a URL that works without a cookie (public bucket, r2.dev, signed URL pasted into chat) you have lost revocation. Keeping the bucket private and routing every byte through the Worker means the same session + space-membership check that guards the JSON API guards the pixels — and <img src="/api/…"> on the same origin sends the session cookie for free, so nothing changes on the client, in the CSP, or in the auth model.
When to use this skill
- Adding photo/image upload to a Workers + Hono + D1 app where the images belong to a space/family and must not be reachable without a session
- You're deciding between R2, Cloudflare Images,
/cdn-cgi/imagetransformations, and presigned S3 URLs and want the 2026-08 numbers, not folklore - Symptoms:
Authentication error [code: 10000]on/accounts/<id>/r2/buckets/<name>duringwrangler deploy(or a Workers Builds build) right after adding anr2_bucketsbinding- An image uploaded under
vite devis 404 underwrangler dev(or in e2e) — or vice versa TS2358: The left-hand side of an 'instanceof' expression must be of type 'any'…onfile instanceof Filein the Worker- A photo taken on an iPhone uploads fine but is a broken image on Android/Chrome (HEIC)
- Portrait phone photos come out sideways after upload
- Planning thumbnails and wondering whether the Images binding will cost money (Free plan: it won't — it errors with
9422instead)
Do not use for: public marketing assets (put them in the Assets binding or a public bucket), video or multi-GB objects (multipart upload, different limits), third-party direct-to-bucket uploads at scale (presigned URLs — deliberately rejected here, see the matrix), or apps without the per-space authorization model.
Deliverables (completion criteria)
- [ ]
wrangler.jsonchasr2_buckets: [{ binding, bucket_name }]; the bucket exists (wrangler r2 bucket create); the deploy/build token hasAccount / Workers R2 Storage / Edit - [ ] Bucket is private (no public access, no
r2.devdomain, no custom domain); every read goes throughGET /api/<parent>/:id/attachments/:attachmentId - [ ] Keys follow
<prefix>/<spaceId>/<parentId>/<attachmentId>with no extension; content type lives in R2httpMetadataand the D1 row - [ ] Upload route: multipart guard →
filenarrowing → size cap (413) → magic-bytes allowlist (415) →put→ INSERT, with a compensatingdeleteif the INSERT throws - [ ] Serve route: session → space membership → parent row → attachment row, then
get(key, { onlyIf }); headersContent-Type(DB),Content-Length(obj.size),ETag(obj.httpEtag),Cache-Control: private, max-age=3600,X-Content-Type-Options: nosniff; 304 on precondition failure; 404 when the object is missing - [ ] Delete: R2
deletebefore the DB delete (never the other way round); parent delete collects keys and uses the array form ofdelete - [ ] Client downscales to ≤ 1600 px JPEG (and a 320 px thumb) via canvas before upload — EXIF/GPS gone, ~200–400 KB per photo
- [ ] HEIC policy decided and written down (default here: reject on the server with a clear message; the client converts what it can decode)
- [ ] Backup decision recorded (default: accept — the phones keep the originals; see the matrix)
- [ ] One e2e path: upload →
<img>200 → cross-user 404 → delete → 404 - [ ] Every
UNVERIFIED:bullet below was confirmed or corrected in the consuming project, and this skill was updated
The decision in one table
Numbers verified 2026-08-22 (sources and the full matrix in references/decision-matrix.md).
| Option | Authz possible? | Cost at family scale | Verdict | |
|---|---|---|---|---|
| Private R2 + Worker proxy | Yes — same middleware as the API | $0: free tier is 10 GB-month, 1M Class A, 10M Class B ops/month, egress free | Chosen | |
Public bucket / r2.dev / custom domain | No — URL = access | $0 | Rejected: private photos | |
| Cloudflare Images (stored) | Signed URLs or binding | $5 per 100k stored + $1 per 100k delivered, monthly | Rejected: fixed cost for ~100 photos/month | |
/cdn-cgi/image/... URL transformations | No — needs a public origin | 5,000 unique transformations/month free | Unusable behind authz | |
| Images binding (transform in the Worker) | Yes — it's just bytes in the Worker | 5,000 unique/month free; Free plan returns error 9422 beyond that (no charge); Paid $0.50 per 1,000 | Optional thumbnail path, see below | |
| Presigned S3 URLs (browser → R2 direct) | Per-URL, time-boxed | $0 but a second token type (R2 API token) | Rejected: nothing to gain at family scale |
Platform ceilings that matter: request body ≤ 100 MB on Free/Pro (so a 10 MB app cap is a policy, not a limit); Workers Free allows 50 subrequests per invocation.
Wiring: binding, bucket, token, local state
- Create the bucket on the host (needs
wrangler login; the sandbox has no credentials):pnpm exec wrangler r2 bucket create <app>-photos— optionally--location apacas a placement hint. Deploy performs an existence check, so the bucket must exist before the first deploy with the binding. - Token permission: the
r2_bucketsbinding needsAccount / Workers R2 Storage / Editon whatever token deploys — the GH ActionsCLOUDFLARE_API_TOKEN(matrix incloudflare-api-token-permissions) or the Workers Builds build token. The token Workers Builds generates via Create new token already carriesWorkers R2 Storage (edit)(docs + dashboard notice, 2026-08-23 — seecloudflare-workers-builds-keyless-deploy0.3.0); only an older or hand-made token may lack it — then extend it in place, don't regenerate. Missing it →Authentication error [code: 10000]on/accounts/<id>/r2/buckets/<name>. - Local dev is fully simulated (Miniflare) — unlike the AI binding, an R2 binding does not force a remote session, so uploads work credential-free in the sandbox. Objects live under
.wrangler/state/v3/r2/<bucket_name>/next to the D1 sqlite; the same--persist-to .wrangler/staterule fromcloudflare-workers-e2e-playwrightapplies, otherwisevite devandwrangler dev --config dist/…see two different buckets and uploads "disappear". - Types:
PHOTOS_BUCKET: R2BucketinBindings(global type viawrangler types).
Key scheme and the attachments row
- No extension. The content type is validated once at upload and stored in R2
httpMetadata.contentTypeand the D1 row; the serve route never guesses from the key - The
spaceIdprefix meanslist({ prefix: "photos/<spaceId>/" })can audit or wipe one family's objects without touching another's - D1 row (
attachments):id,record_id(FK → the parent that carriesspace_id,ON DELETE CASCADE),r2_key,thumb_key(nullable),content_type,size_bytes,width,height,original_filename,created_by,created_at. Schema and routes in references/worker-routes.md. For matatabetai: parent =meals, table =meal_photos
Upload route — validate before put, put before INSERT
Order of checks (each one returns before the next runs):
- Parent row resolved through
memberSpaceIds(404 if it isn't in one of your spaces — existence-hiding, same rule as every other route) Content-Typeheader starts withmultipart/form-data, else 400 —c.req.formData()throws on anything else and you'd get an opaque 500const file = form.get("file"); rejectnullandstring(400). Don't writefile instanceof File— the Worker tsconfig fails it with TS2358; excluding the other two members ofFormDataEntryValuenarrows toFilefile.size === 0→ 400;file.size > MAX_IMAGE_BYTES(10 MB) → 413attachment_too_large- Sniff the first 12 bytes (
FF D8 FFJPEG,89 50 4E 47 0D 0A 1A 0APNG,RIFF….WEBP,ftyp+ HEIF brand) and allow onlyimage/jpeg/image/png/image/webp→ 415attachment_type_not_allowedotherwise.file.typeis whatever the client said; store the sniffed type, notfile.type PHOTOS_BUCKET.put(key, bytes, { httpMetadata: { contentType } })— then the optionalthumbfield the same way- INSERT the row. If the INSERT throws,
deletethe object(s) you just put and rethrow — an object without a row is an orphan nobody can ever delete through the app - 201 with the row plus its serve URL
Serve route — authorize before touching R2
- The chain is N hops of "child row points at the row I already trusted"; only the first hop checks space membership. Every miss is 404, never 403
onlyIf: c.req.raw.headerslets R2 evaluate the browser'sIf-None-Match/If-Modified-Since; when the precondition fails R2 returns anR2Objectwithoutbody→ respond304withETag+Cache-Control. (Documented R2 API; not yet exercised in the source projects — see UNVERIFIED)- Headers:
Content-Typefrom the DB row,Content-Length: obj.size(not the DB value — they drift after a re-upload or a cached transform),ETag: obj.httpEtag,Cache-Control: private, max-age=3600,Content-Disposition: inline,X-Content-Type-Options: nosniff nullfromgetwith a row present = DB/R2 inconsistency → 404 andconsole.error(it should never happen with the delete ordering below)- Never
publicand never the Cache API: the edge cache is keyed by URL, not by cookie — one cachedpublicresponse is every family's photo for an hour
Delete — R2 first (best-effort), then D1
- Single attachment:
delete([r2Key, thumbKey])→ DB delete. If R2 throws, the row survives and the user retries; the reverse order turns a transient R2 failure into a permanent 404 row - Parent delete:
SELECT r2_key, thumb_key WHERE record_id = ?→ onedelete(keys[])call (array form, up to 1,000 keys — one call instead of N, which also matters under the Free plan's 50-subrequest cap) → delete the parent (rows cascade) - Orphans are acceptable at family scale; an optional weekly sweep (
list({ prefix: "photos/" })minus the rows, skipping objects uploaded in the last hour) is sketched in references/e2e-and-ops.md — cron plumbing percloudflare-cron-to-discord
Client — downscale, strip EXIF, then FormData
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/cloudflare-r2-private-image-upload/SKILL.md
Popularity
- 7-day trend score
- 5
Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/okayus/okayus-skills/cloudflare-r2-private-image-upload)