Co-Authored-By: Claude Fable 5.2 <[email protected]>
16 KiB
storage — media on Cloudflare R2
Offload media (images, files) to Cloudflare R2 instead of the local disk. R2 is
S3-compatible; the plugin provides buildR2Storage, which reads the settings from .env
and configures the adapter.
Storage is infrastructure, not content. R2 settings (keys, bucket) go into
.env— like DATABASE_URI, PAYLOAD_SECRET, GRAPH_*. NOT into the admin panel (they are agency secrets, bound at startup, the editor does not change them).
Form files are not stored. A file a visitor attaches to a form (
forms.attachments) is checked, e-mailed to the company and dropped — it never becomes a Media record and never reaches R2 or the disk. Nothing on this page applies to it; see forms.md "Files".
.env variables
Where to get the values: Cloudflare → R2 → bucket (name), Overview → S3 API (endpoint https://<ACCOUNT_ID>.r2.cloudflarestorage.com), Manage R2 API Tokens → "Object Read & Write" (a key pair; the secret is shown once). All 4 variables → R2; any missing → local disk (partial configuration = a warning in the log).
R2_BUCKET=bucket-name
R2_ENDPOINT=https://<ACCOUNT_ID>.r2.cloudflarestorage.com
R2_ACCESS_KEY_ID=<access-key-id>
R2_SECRET_ACCESS_KEY=<secret-access-key>
R2_PUBLIC_URL= # empty = media served through the app (default); a media domain → see "Public access"
Wiring (payload.config.ts)
pnpm add @payloadcms/storage-s3 # optional plugin peer; same version as payload (pnpm.overrides)
import { buildR2Storage } from '@intecion/ipal-kit'
import { s3Storage } from '@payloadcms/storage-s3'
export default buildConfig({
// ...
plugins: [
ipalKit({ /* ... */ }),
buildR2Storage(['media'], { s3Storage }), // collection slugs + the INJECTED adapter
],
})
buildR2Storage takes a list of upload collections (default ['media']). If
you have more file collections: buildR2Storage(['media', 'documents'], { s3Storage }).
The adapter is injected (since 1.8.1) — the plugin does not import
@payloadcms/storage-s3, because it is an optional dependency: projects on local disk
don't install it. The same pattern as payloadTotp in 2FA and NextResponse in the
proxy. When the R2 env is set but s3Storage was not passed, startup ends with a
clear error (instead of silently writing media to the container disk, which disappears
on redeploy). The older call buildR2Storage(['media']) without an adapter
works only without the R2 env.
Behavior (fallback)
- All 4 variables → media in R2.
- No variables → fallback to local disk (dev works without R2, zero configuration).
- Some of the variables → a warning in the log + fallback (partial configuration = probably a mistake).
- Only
R2_PUBLIC_URL(absolute, outside production) → read-only media (1.12.2): file URLs from the media domain, upload and delete blocked (403). For local dev connected to the production database — you see images, and nothing reaches the real bucket.
The import map does not depend on env (1.12.2). When the project injects s3Storage, the adapter is
always registered — without R2 as disabled (enabled: false, local disk). storage-s3 still
adds its S3ClientUploadHandler to the import map then, so pnpm dev /
generate:importmap without R2_* writes the same importMap.js as production. Up to 1.12.1, dev without
R2 removed that entry, and the production admin panel (with R2) rendered a blank page with no console error.
ipal-audit reports an import map without the handler.
This is the "degrade gracefully" pattern — like mailAdapter, which falls back to SMTP when there is no Graph. The project works whether or not R2 is configured.
Public access — how media reach the browser (IMPORTANT)
R2 is private by default: the S3 endpoint (<ACCOUNT_ID>.r2.cloudflarestorage.com) accepts uploads but does not
serve files publicly. R2_PUBLIC_URL decides where the URLs Payload generates point:
R2_PUBLIC_URL |
Media URL | DNS / Cloudflare | Use |
|---|---|---|---|
| empty (default) | /api/media/file/<name> on the site's own domain — Payload streams the file from R2 |
nothing | every project whose zone is on our DNS servers |
https://<media domain> |
https://<media domain>/<name> — straight from R2 via Cloudflare |
the domain's zone in our Cloudflare account + bucket Custom Domain | media-heavy sites that need the CDN |
https://pub-….r2.dev |
r2.dev URL | none | dev/testing only — rate-limited, no cache |
Why not media.klient.pl? An R2 bucket Custom Domain must belong to a zone in the same Cloudflare account,
with full setup (nameservers at Cloudflare). A CNAME ("partial") setup for a zone kept on other DNS servers needs a
Business or Enterprise plan. Our clients' zones are on our own servers, so a subdomain of the client's domain
cannot be attached to the bucket. (A reverse proxy on the Coolify server, media.klient.pl → the bucket, is
possible but adds moving parts.) DNS checklist: deployment.md §6 row 9.
Default: media through the app (R2_PUBLIC_URL empty)
With all 4 R2 keys and no public URL, buildR2Storage gives the collections plain offload (true): files are
stored in R2, and Payload's file route /api/media/file/<name> (/api/<slug>/file/<name> for other upload
collections) reads them from the bucket. The stored URL is site-relative (our projects do not set serverURL in
payload.config.ts).
Requirements and consequences:
- Public read on the upload collection — the file route checks the collection's
readaccess, and Payload's default is "logged-in users only" → anonymous visitors (and next/image) get 403. Addaccess: { read: () => true }toMedia(and every other public upload collection). - Env validation — nothing to change:
ipalEnvRules({ storage: true })treatsR2_PUBLIC_URLas optional (storage: { requirePublicUrl: true }makes it required, for projects that always use a media domain). - next/image treats the URLs as local images; CSP
img-src 'self'already covers them;MediaPreconnectrenders nothing (same origin); the plugin's sitemap / JSON-LD helpers make relative image URLs absolute. - Cost: every original file request passes through the app (bandwidth/CPU). Page images go through
/_next/image, whose optimized variants are cached (minimumCacheTTL31 days,buildImagesConfig); heavy video/PDF traffic → consider option 2.
Check: upload an image, its URL in the panel is /api/media/file/<name>;
curl -sI https://klient.pl/api/media/file/<name> → 200 (not 403) without being logged in.
Option: a media domain on Cloudflare (R2_PUBLIC_URL set)
For sites with heavy media: a separate domain whose zone is in our Cloudflare account (e.g. klient-media.com, or
a subdomain of one shared agency media domain). Gives the Cloudflare CDN, cache rules and no app traffic.
- Cloudflare Dashboard → R2 → pick the bucket
- Settings tab → Public access section → Custom Domains
- Connect Domain → enter the domain, e.g.
media.klient-media.com(its zone must be in this account) - Cloudflare adds the DNS record automatically and issues a certificate. Wait until the status = Active.
- From then on files are public at
https://media.klient-media.com/<file-key>.
Then set the URL in the project:
# .env / Coolify
R2_PUBLIC_URL=https://media.klient-media.com
# dev with a /media → bucket rewrite: R2_PUBLIC_URL=/media (outside production only; env.md)
buildR2Storage passes it as generateFileURL → Payload stores https://media.klient-media.com/<file> URLs.
buildImagesConfig, buildCsp({ r2Url }) and MediaPreconnect read the same variable.
Verification: upload an image; its URL in the panel is https://media.klient-media.com/... (not
/api/media/file/..., not *.r2.cloudflarestorage.com); the URL opens in a browser (not 403); <img src> works.
403 despite a custom domain: custom domain not Active yet (wait for the certificate), or created but not
connected to the bucket (bucket Settings → Custom Domains), or the URL in the panel still points elsewhere
(R2_PUBLIC_URL missing at runtime → redeploy).
Why not "r2.dev"
The quick public URL *.r2.dev is rate-limited, does not go through the Cloudflare cache, and is not your
domain — use it only for a quick test, never in production.
Media caching on the media domain (Cache Rule — mandatory with option 2)
Files in R2 have no Cache-Control header: @payloadcms/storage-s3 sets only
ContentType and ACL on upload, with no option for headers. Cloudflare then gives the browser the default 4 h —
Lighthouse: "Use efficient cache lifetimes" (video, logo, backgrounds downloaded
again on every visit after 4 h). File names are stable (a new version = a new file from normalizeFilename),
so a long lifetime is safe.
Cloudflare → the media domain's zone → Caching → Cache Rules → Create rule:
- When incoming requests match:
Hostnameequalsmedia.klient-media.com(the domain fromR2_PUBLIC_URL); - Cache eligibility: Eligible for cache;
- Edge TTL: Ignore cache-control header and use this TTL → 1 year;
- Browser TTL: Override origin and use this TTL → 1 year.
Check (after a few minutes):
curl -sI https://media.klient-media.com/<file> | grep -iE 'cache-control|cf-cache-status'
# cache-control: max-age=31536000 cf-cache-status: HIT (on the second request)
Replacing a file under THE SAME name (rare — the admin panel assigns a new one) needs Caching → Purge → Custom (URL).
Migrating existing media
If the project had media locally and you switch to R2 — new uploads go to R2,
but the OLD ones stay on disk (and disappear on a redeploy without a volume). Before
switching in production, move the existing files to the bucket (e.g. rclone
or manually through the R2 dashboard), otherwise old images disappear.
Verification
# after wiring and setting .env:
pnpm dev
# upload an image in the admin panel (Media) → check in Cloudflare R2 that the file appeared
The media domain root returns 404 (this is normal — option 2 only)
media.klient-media.com/plik.jpg → R2 returns the file. But media.klient-media.com/ (the bare root,
no file) → 404, because R2 has no object at the root. This is NORMAL R2
behavior, not an error.
SEO audits (Screaming Frog) sometimes report this 404 — the crawler sees file
URLs (media.../logo.svg) and tries the root. But:
- Do NOT link to the bare root
media.klient-media.com/— only to files. The code should never havemedia.klient-media.com/without a file name. - The media root 404 does not hurt SEO of the main domain (Google indexes klient.pl, not media.klient-media.com). Nobody lands on the media root.
The plugin will not fix this — the media subdomain is an R2/Cloudflare service, not the Next app. Requests to media.klient-media.com never reach your code.
If you want it "clean" in Search Console (optional): Cloudflare → Rules →
Redirect Rules → when hostname = media.klient-media.com and path = / → 301 to
klient.pl. A one-off in the CF dashboard. But it is cosmetic — the media root 404 is
harmless.
Dev on local disk AND on R2 (seeding during development)
The fallback (no variables → local disk) means that dev works in both modes:
- Dev without R2 in .env → media on local disk. Quick start, zero configuration.
- Dev with R2 in .env → media in R2 already during development. Useful when you seed content in dev and want it to land in the bucket right away (e.g. a shared dev bucket, or testing the real flow before production).
You switch modes simply by the presence of the R2 variables in .env. The same code;
buildR2Storage detects it by itself. You don't need to change anything in the config between modes.
If you seed to R2 in dev — remember it is a real bucket. Use a separate dev bucket (not the production one), so test data does not mix with real data.
The Media collection — file names, oversized uploads, placeholders
normalizeFilenameHook, buildOptimizeUploadHook / buildOptimizeUploadField,
buildMediaPlaceholderHook / buildMediaPlaceholderField, mediaImageProps, videoProps,
MEDIA_SIZES — described in media.md. All hooks run before the storage
layer, so they work the same on local disk and in R2.
Preconnect to the media domain (performance)
The MediaPreconnect component generates <link rel="preconnect"> + dns-prefetch
for the media domain (R2_PUBLIC_URL) — the browser opens the TLS/DNS connection
to the CDN in advance, before it meets the first <img>. Gain ~150–300 ms on the first
image.
// layout.tsx — at the TOP of <body>, NOT in an explicit <head>
import { MediaPreconnect } from '@intecion/ipal-kit/rsc'
<body className={...}>
<MediaPreconnect />
{children}
</body>
Do NOT put it in an explicit
<head>! A hard-coded<head><MediaPreconnect/></head>in an App Router layout forces the head to close early — before the page generates its metadata — so title/canonical/hreflang end up in<body>(crawlers don't see them). React 19 hoists<link rel="preconnect">into<head>by itself, so rendering in<body>is correct. See seo.md (metadata in head).
It reads the domain from R2_PUBLIC_URL (the same source as buildR2Storage) — zero
hard-coding, one source of truth. When R2_PUBLIC_URL is not set (media through the app or local disk,
no CDN) or is a path (/media) → it renders nothing. SiteProviders wires it by itself
(preconnect={false} turns it off) — wire it manually only with your own layout without SiteProviders. Changing the media domain = changing one env
variable; the component follows automatically.
Do NOT hard-code
<link rel="preconnect" href="https://media.klient-media.com">manually in the layout — that bakes the client's domain into the code. Use MediaPreconnect, which takes it from env.
next.config.ts — images and upload headers
buildImagesConfig({ serverUrl?, production?, publicUrl?, extraHosts? })→imagesinnext.config.ts:formatsAVIF + WebP,minimumCacheTTL31 days,remotePatternsfromR2_PUBLIC_URL(publicUrl) andextraHosts(https). Media served by the app —/api/media/file/**onNEXT_PUBLIC_SERVER_URL(serverUrl) — are allowed outside production (production, defaultNODE_ENV === 'production') and in production whenR2_PUBLIC_URLis empty (the default without R2: Payload gives absolute URLs on the site's own host, which next/image would refuse with 400). Outside production alsodangerouslyAllowLocalIP: truefor localhost / private networks (Next 16 rejects them otherwise); a production build on localhost never gets it — setproduction: falsefor such a test run. Spread the result and override:images: { ...buildImagesConfig(), /* your own */ }.buildUploadSecurityHeaders({ collections? })(default['media']) → headers for/api/<slug>/file/:path*: sandbox CSP +nosniff(uploaded SVG without scripts). security.md.
YouTube without loading the iframe — YouTubeEmbed
<YouTubeEmbed videoId title playLabel note? poster? classNames? /> from @intecion/ipal-kit/client —
the iframe loads only after a click.
Turn off / override
buildR2Storage— opt-in: not wired intoplugins→ media go to Payload's disk; withoutR2_*also disk. It returns a plains3Storageplugin — need other storage-s3 options (e.g.prefix,clientUploads)? Calls3Storageyourself instead ofbuildR2Storage.MediaPreconnect— on by default inSiteProviders, turn off withpreconnect={false}.buildImagesConfig/buildUploadSecurityHeaders— return plain objects to spread and override; nothing is wired automatically.