import type { CollectionConfig, Plugin } from 'payload' import { APIError } from 'payload' type GenerateFileURL = (args: { filename: string; prefix?: string }) => string /** * Minimal shape of `s3Storage` from @payloadcms/storage-s3 — the plugin never * imports that package (it's optional: projects on local disk don't install it). * The project injects the real function; TypeScript checks it fits this shape. */ export type S3StorageFactory = (options: { bucket: string collections: Record config: { credentials: { accessKeyId: string; secretAccessKey: string } endpoint: string forcePathStyle: boolean region: string } /** false = registered but inactive: no S3 client, local disk, admin import map unchanged. */ enabled?: boolean }) => Plugin export type BuildR2StorageDeps = { /** `import { s3Storage } from '@payloadcms/storage-s3'` — required when R2 env is set. */ s3Storage?: S3StorageFactory } /** * Cloudflare R2 media storage — configured from environment variables (agency * infrastructure, not per-project panel data). R2 is S3-compatible, so we use * @payloadcms/storage-s3 pointed at the R2 endpoint. * * Storage is infrastructure (like the database or PAYLOAD_SECRET): it binds at * boot, and its credentials are agency-owned — so it lives in .env, not the * panel. See docs/storage.md for the required variables. * * Returns the storage plugin when all R2 vars are present; otherwise returns a * no-op passthrough so the project falls back to Payload's default local disk * storage (useful in dev without R2). This mirrors how mailAdapter degrades * gracefully when a transport isn't configured. * * The S3 adapter is INJECTED by the project (same pattern as 2FA / NextResponse): * * import { s3Storage } from '@payloadcms/storage-s3' * plugins: [buildR2Storage(['media'], { s3Storage })] * * A static import here would make @payloadcms/storage-s3 mandatory for every * project — including ones on local disk — because this module is exported * from the package's main entry. * * @param collections - slugs of upload collections to offload to R2 (e.g. ['media']) * @param deps - `{ s3Storage }` from @payloadcms/storage-s3 (needed only when R2 env is set) */ export const buildR2Storage = ( collections: string[] = ['media'], deps: BuildR2StorageDeps = {}, ): Plugin => { const bucket = process.env.R2_BUCKET const endpoint = process.env.R2_ENDPOINT const accessKeyId = process.env.R2_ACCESS_KEY_ID const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY const { s3Storage } = deps // Any missing → local disk. The adapter is still REGISTERED (enabled: false) when the // project injects it: storage-s3 adds its admin client handler to the import map even // when disabled, so `pnpm dev` / `generate:importmap` without R2 env writes the same // importMap.js as production. Before 1.12.2 a no-op was returned here — an import map // generated in dev lacked S3ClientUploadHandler and the production admin rendered blank. if (!bucket || !endpoint || !accessKeyId || !secretAccessKey) { const readOnly = readOnlyPublicUrl({ accessKeyId, bucket, endpoint, secretAccessKey }) const disabled: Plugin | undefined = s3Storage ? s3Storage({ bucket: bucket ?? '', collections: Object.fromEntries(collections.map((slug) => [slug, true as const])), config: { credentials: { accessKeyId: accessKeyId ?? '', secretAccessKey: secretAccessKey ?? '' }, endpoint: endpoint ?? '', forcePathStyle: true, region: 'auto', }, enabled: false, }) : undefined return (config) => { if (readOnly) { console.warn( `[ipal] R2 storage: read-only media from ${readOnly} (R2_PUBLIC_URL without credentials) — ` + 'uploads are disabled. Set all R2_* to upload, or none for local disk.', ) } else if (bucket || endpoint || accessKeyId || secretAccessKey) { // Only warn when SOME vars are set (partial config = likely a mistake). console.warn( '[ipal] R2 storage: incomplete env (need R2_BUCKET, R2_ENDPOINT, ' + 'R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY). Falling back to local disk.', ) } const next = disabled ? disabled(config) : config return readOnly ? withReadOnlyMedia(next as Parameters[0], collections, readOnly) : next } } // Public URL for served media. R2 is private by default; its S3 endpoint only // accepts uploads and won't serve files (403). With a custom domain // (media.klient.pl → bucket) set R2_PUBLIC_URL so Payload generates URLs // pointing there. Without it, uploads work but images don't display publicly. // See docs/storage.md. // Site-relative value ('/media', dev only — ipalEnvRules rejects it in production) // → prefixed with NEXT_PUBLIC_SERVER_URL so Payload still stores absolute URLs. const rawPublicUrl = process.env.R2_PUBLIC_URL?.trim().replace(/\/$/, '') // strip trailing slash const serverUrl = process.env.NEXT_PUBLIC_SERVER_URL?.trim().replace(/\/$/, '') const publicUrl = rawPublicUrl?.startsWith('/') && serverUrl ? `${serverUrl}${rawPublicUrl}` : rawPublicUrl // generateFileURL is a PER-COLLECTION option in @payloadcms/storage-s3 (not a // top-level one) — R2 needs it to point served URLs at the custom domain // instead of the private S3 endpoint. Each collection gets either `true` // (plain offload) or an object carrying generateFileURL when a public URL is set. const generateFileURL = publicUrl ? ({ filename, prefix }: { filename: string; prefix?: string }) => [publicUrl, prefix, filename].filter(Boolean).join('/') : undefined // R2 env is complete → the adapter is required. Fail loudly at boot rather // than silently storing media on the container disk (lost on redeploy). if (!s3Storage) { throw new Error( '[ipal] R2 storage: R2_* env is set but the S3 adapter was not injected. ' + "Install @payloadcms/storage-s3 and pass it: buildR2Storage(['media'], { s3Storage }) " + "with `import { s3Storage } from '@payloadcms/storage-s3'`. See docs/storage.md.", ) } const collectionsConfig: Record = {} for (const slug of collections) { collectionsConfig[slug] = generateFileURL ? { generateFileURL } : true } return s3Storage({ bucket, collections: collectionsConfig, config: { credentials: { accessKeyId, secretAccessKey }, endpoint, region: 'auto', // R2 uses 'auto' // R2 requires path-style addressing for S3 compatibility. forcePathStyle: true, }, }) } /** * Read-only media: outside production, R2_PUBLIC_URL (absolute) with none of the * credentials → files are read from the public domain. For a local dev pointed at * a production database: images show, nothing can be uploaded to (or deleted from) * the real bucket. Returns the base URL, or null when the mode doesn't apply. */ function readOnlyPublicUrl(env: { accessKeyId?: string bucket?: string endpoint?: string secretAccessKey?: string }): null | string { if (process.env.NODE_ENV === 'production') {return null} if (env.accessKeyId || env.bucket || env.endpoint || env.secretAccessKey) {return null} const url = process.env.R2_PUBLIC_URL?.trim().replace(/\/$/, '') return url && /^https?:\/\/[^/\s]+/i.test(url) ? url : null } type UploadDoc = { filename?: null | string sizes?: Record thumbnailURL?: null | string url?: null | string } function withReadOnlyMedia( config: Parameters[0], collections: string[], publicUrl: string, ): Parameters[0] { const fileUrl = (filename: string) => `${publicUrl}/${encodeURIComponent(filename)}` return { ...config, collections: (config.collections ?? []).map((collection): CollectionConfig => { if (!collections.includes(collection.slug)) {return collection} return { ...collection, hooks: { ...collection.hooks, afterRead: [ ...(collection.hooks?.afterRead ?? []), ({ doc }: { doc: UploadDoc }) => { if (!doc?.filename) {return doc} doc.url = fileUrl(doc.filename) if (doc.thumbnailURL) { const thumb = doc.sizes?.thumbnail?.filename doc.thumbnailURL = thumb ? fileUrl(thumb) : doc.url } for (const size of Object.values(doc.sizes ?? {})) { if (size?.filename) {size.url = fileUrl(size.filename)} } return doc }, ], beforeOperation: [ ...(collection.hooks?.beforeOperation ?? []), ({ args, operation }) => { const req = (args as { req?: { file?: unknown } }).req if (operation === 'delete' || ((operation === 'create' || operation === 'update') && req?.file)) { throw new APIError( 'Media is read-only here (R2_PUBLIC_URL without R2 credentials). Set all R2_* to upload or delete files.', 403, ) } return args }, ], }, } }), } }