R2 storage (generateFileURL per-collection) + filename normalization

This commit is contained in:
2026-08-27 18:57:14 +02:00
parent 247b849759
commit c6730335ef
3 changed files with 38 additions and 41 deletions
+19 -20
View File
@@ -31,32 +31,31 @@ import { s3Storage } from '@payloadcms/storage-s3';
return config; return config;
}; };
} }
// s3Storage wants Record<string, true> (the literal true, per collection), // Public URL for served media. R2 is private by default; its S3 endpoint only
// not Record<string, boolean>. Object.fromEntries widens true → boolean, so // accepts uploads and won't serve files (403). With a custom domain
// build the map with an explicitly-typed accumulator to keep the literal.
const collectionsConfig = {};
for (const slug of collections){
collectionsConfig[slug] = true;
}
// Public URL for served media. R2 is private by default; with a custom domain
// (media.klient.pl → bucket) set R2_PUBLIC_URL so Payload generates URLs // (media.klient.pl → bucket) set R2_PUBLIC_URL so Payload generates URLs
// pointing there instead of the private S3 endpoint (which 403s on the front). // pointing there. Without it, uploads work but images don't display publicly.
// Without it, uploads work but images don't display publicly. See docs/storage.md. // See docs/storage.md.
const publicUrl = process.env.R2_PUBLIC_URL?.replace(/\/$/, '') // strip trailing slash const publicUrl = process.env.R2_PUBLIC_URL?.replace(/\/$/, '') // strip trailing slash
; ;
// 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 })=>[
publicUrl,
prefix,
filename
].filter(Boolean).join('/') : undefined;
const collectionsConfig = {};
for (const slug of collections){
collectionsConfig[slug] = generateFileURL ? {
generateFileURL
} : true;
}
return s3Storage({ return s3Storage({
bucket, bucket,
collections: collectionsConfig, collections: collectionsConfig,
...publicUrl ? {
// generateFileURL overrides the stored/returned URL to the CDN domain.
// Params come from Payload's storage plugin; type them explicitly since
// the callback shape isn't inferred here (would be implicit any).
generateFileURL: ({ filename, prefix })=>[
publicUrl,
prefix,
filename
].filter(Boolean).join('/')
} : {},
config: { config: {
credentials: { credentials: {
accessKeyId, accessKeyId,
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/storage/buildR2Storage.ts"],"sourcesContent":["import type { Plugin } from 'payload'\n\nimport { s3Storage } from '@payloadcms/storage-s3'\n\n/**\n * Cloudflare R2 media storage — configured from environment variables (agency\n * infrastructure, not per-project panel data). R2 is S3-compatible, so we use\n * @payloadcms/storage-s3 pointed at the R2 endpoint.\n *\n * Storage is infrastructure (like the database or PAYLOAD_SECRET): it binds at\n * boot, and its credentials are agency-owned — so it lives in .env, not the\n * panel. See docs/storage.md for the required variables.\n *\n * Returns the storage plugin when all R2 vars are present; otherwise returns a\n * no-op passthrough so the project falls back to Payload's default local disk\n * storage (useful in dev without R2). This mirrors how mailAdapter degrades\n * gracefully when a transport isn't configured.\n *\n * @param collections - slugs of upload collections to offload to R2 (e.g. ['media'])\n */\nexport const buildR2Storage = (collections: string[] = ['media']): Plugin => {\n const bucket = process.env.R2_BUCKET\n const endpoint = process.env.R2_ENDPOINT\n const accessKeyId = process.env.R2_ACCESS_KEY_ID\n const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY\n\n // Any missing → skip R2, fall back to local disk. Warn so it's not silent.\n if (!bucket || !endpoint || !accessKeyId || !secretAccessKey) {\n return (config) => {\n // Only warn when SOME vars are set (partial config = likely a mistake).\n if (bucket || endpoint || accessKeyId || secretAccessKey) {\n console.warn(\n '[ipal] R2 storage: incomplete env (need R2_BUCKET, R2_ENDPOINT, ' +\n 'R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY). Falling back to local disk.',\n )\n }\n return config\n }\n }\n\n // s3Storage wants Record<string, true> (the literal true, per collection),\n // not Record<string, boolean>. Object.fromEntries widens true → boolean, so\n // build the map with an explicitly-typed accumulator to keep the literal.\n const collectionsConfig: Record<string, true> = {}\n for (const slug of collections) {\n collectionsConfig[slug] = true\n }\n\n // Public URL for served media. R2 is private by default; with a custom domain\n // (media.klient.pl → bucket) set R2_PUBLIC_URL so Payload generates URLs\n // pointing there instead of the private S3 endpoint (which 403s on the front).\n // Without it, uploads work but images don't display publicly. See docs/storage.md.\n const publicUrl = process.env.R2_PUBLIC_URL?.replace(/\\/$/, '') // strip trailing slash\n\n return s3Storage({\n bucket,\n collections: collectionsConfig,\n ...(publicUrl\n ? {\n // generateFileURL overrides the stored/returned URL to the CDN domain.\n // Params come from Payload's storage plugin; type them explicitly since\n // the callback shape isn't inferred here (would be implicit any).\n generateFileURL: ({ filename, prefix }: { filename: string; prefix?: string }) =>\n [publicUrl, prefix, filename].filter(Boolean).join('/'),\n }\n : {}),\n config: {\n credentials: { accessKeyId, secretAccessKey },\n endpoint,\n region: 'auto', // R2 uses 'auto'\n // R2 requires path-style addressing for S3 compatibility.\n forcePathStyle: true,\n },\n })\n}\n"],"names":["s3Storage","buildR2Storage","collections","bucket","process","env","R2_BUCKET","endpoint","R2_ENDPOINT","accessKeyId","R2_ACCESS_KEY_ID","secretAccessKey","R2_SECRET_ACCESS_KEY","config","console","warn","collectionsConfig","slug","publicUrl","R2_PUBLIC_URL","replace","generateFileURL","filename","prefix","filter","Boolean","join","credentials","region","forcePathStyle"],"mappings":"AAEA,SAASA,SAAS,QAAQ,yBAAwB;AAElD;;;;;;;;;;;;;;;CAeC,GACD,OAAO,MAAMC,iBAAiB,CAACC,cAAwB;IAAC;CAAQ;IAC9D,MAAMC,SAASC,QAAQC,GAAG,CAACC,SAAS;IACpC,MAAMC,WAAWH,QAAQC,GAAG,CAACG,WAAW;IACxC,MAAMC,cAAcL,QAAQC,GAAG,CAACK,gBAAgB;IAChD,MAAMC,kBAAkBP,QAAQC,GAAG,CAACO,oBAAoB;IAExD,2EAA2E;IAC3E,IAAI,CAACT,UAAU,CAACI,YAAY,CAACE,eAAe,CAACE,iBAAiB;QAC5D,OAAO,CAACE;YACN,wEAAwE;YACxE,IAAIV,UAAUI,YAAYE,eAAeE,iBAAiB;gBACxDG,QAAQC,IAAI,CACV,qEACE;YAEN;YACA,OAAOF;QACT;IACF;IAEA,2EAA2E;IAC3E,4EAA4E;IAC5E,0EAA0E;IAC1E,MAAMG,oBAA0C,CAAC;IACjD,KAAK,MAAMC,QAAQf,YAAa;QAC9Bc,iBAAiB,CAACC,KAAK,GAAG;IAC5B;IAEA,8EAA8E;IAC9E,yEAAyE;IACzE,+EAA+E;IAC/E,mFAAmF;IACnF,MAAMC,YAAYd,QAAQC,GAAG,CAACc,aAAa,EAAEC,QAAQ,OAAO,IAAI,uBAAuB;;IAEvF,OAAOpB,UAAU;QACfG;QACAD,aAAac;QACb,GAAIE,YACA;YACE,uEAAuE;YACvE,wEAAwE;YACxE,kEAAkE;YAClEG,iBAAiB,CAAC,EAAEC,QAAQ,EAAEC,MAAM,EAAyC,GAC3E;oBAACL;oBAAWK;oBAAQD;iBAAS,CAACE,MAAM,CAACC,SAASC,IAAI,CAAC;QACvD,IACA,CAAC,CAAC;QACNb,QAAQ;YACNc,aAAa;gBAAElB;gBAAaE;YAAgB;YAC5CJ;YACAqB,QAAQ;YACR,0DAA0D;YAC1DC,gBAAgB;QAClB;IACF;AACF,EAAC"} {"version":3,"sources":["../../../src/modules/storage/buildR2Storage.ts"],"sourcesContent":["import type { Plugin } from 'payload'\n\nimport { s3Storage } from '@payloadcms/storage-s3'\n\n/**\n * Cloudflare R2 media storage — configured from environment variables (agency\n * infrastructure, not per-project panel data). R2 is S3-compatible, so we use\n * @payloadcms/storage-s3 pointed at the R2 endpoint.\n *\n * Storage is infrastructure (like the database or PAYLOAD_SECRET): it binds at\n * boot, and its credentials are agency-owned — so it lives in .env, not the\n * panel. See docs/storage.md for the required variables.\n *\n * Returns the storage plugin when all R2 vars are present; otherwise returns a\n * no-op passthrough so the project falls back to Payload's default local disk\n * storage (useful in dev without R2). This mirrors how mailAdapter degrades\n * gracefully when a transport isn't configured.\n *\n * @param collections - slugs of upload collections to offload to R2 (e.g. ['media'])\n */\nexport const buildR2Storage = (collections: string[] = ['media']): Plugin => {\n const bucket = process.env.R2_BUCKET\n const endpoint = process.env.R2_ENDPOINT\n const accessKeyId = process.env.R2_ACCESS_KEY_ID\n const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY\n\n // Any missing → skip R2, fall back to local disk. Warn so it's not silent.\n if (!bucket || !endpoint || !accessKeyId || !secretAccessKey) {\n return (config) => {\n // Only warn when SOME vars are set (partial config = likely a mistake).\n if (bucket || endpoint || accessKeyId || secretAccessKey) {\n console.warn(\n '[ipal] R2 storage: incomplete env (need R2_BUCKET, R2_ENDPOINT, ' +\n 'R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY). Falling back to local disk.',\n )\n }\n return config\n }\n }\n\n // Public URL for served media. R2 is private by default; its S3 endpoint only\n // accepts uploads and won't serve files (403). With a custom domain\n // (media.klient.pl → bucket) set R2_PUBLIC_URL so Payload generates URLs\n // pointing there. Without it, uploads work but images don't display publicly.\n // See docs/storage.md.\n const publicUrl = process.env.R2_PUBLIC_URL?.replace(/\\/$/, '') // strip trailing slash\n\n // generateFileURL is a PER-COLLECTION option in @payloadcms/storage-s3 (not a\n // top-level one) — R2 needs it to point served URLs at the custom domain\n // instead of the private S3 endpoint. Each collection gets either `true`\n // (plain offload) or an object carrying generateFileURL when a public URL is set.\n const generateFileURL = publicUrl\n ? ({ filename, prefix }: { filename: string; prefix?: string }) =>\n [publicUrl, prefix, filename].filter(Boolean).join('/')\n : undefined\n\n const collectionsConfig: Record<string, { generateFileURL: typeof generateFileURL } | true> = {}\n for (const slug of collections) {\n collectionsConfig[slug] = generateFileURL ? { generateFileURL } : true\n }\n\n return s3Storage({\n bucket,\n collections: collectionsConfig,\n config: {\n credentials: { accessKeyId, secretAccessKey },\n endpoint,\n region: 'auto', // R2 uses 'auto'\n // R2 requires path-style addressing for S3 compatibility.\n forcePathStyle: true,\n },\n })\n}\n"],"names":["s3Storage","buildR2Storage","collections","bucket","process","env","R2_BUCKET","endpoint","R2_ENDPOINT","accessKeyId","R2_ACCESS_KEY_ID","secretAccessKey","R2_SECRET_ACCESS_KEY","config","console","warn","publicUrl","R2_PUBLIC_URL","replace","generateFileURL","filename","prefix","filter","Boolean","join","undefined","collectionsConfig","slug","credentials","region","forcePathStyle"],"mappings":"AAEA,SAASA,SAAS,QAAQ,yBAAwB;AAElD;;;;;;;;;;;;;;;CAeC,GACD,OAAO,MAAMC,iBAAiB,CAACC,cAAwB;IAAC;CAAQ;IAC9D,MAAMC,SAASC,QAAQC,GAAG,CAACC,SAAS;IACpC,MAAMC,WAAWH,QAAQC,GAAG,CAACG,WAAW;IACxC,MAAMC,cAAcL,QAAQC,GAAG,CAACK,gBAAgB;IAChD,MAAMC,kBAAkBP,QAAQC,GAAG,CAACO,oBAAoB;IAExD,2EAA2E;IAC3E,IAAI,CAACT,UAAU,CAACI,YAAY,CAACE,eAAe,CAACE,iBAAiB;QAC5D,OAAO,CAACE;YACN,wEAAwE;YACxE,IAAIV,UAAUI,YAAYE,eAAeE,iBAAiB;gBACxDG,QAAQC,IAAI,CACV,qEACE;YAEN;YACA,OAAOF;QACT;IACF;IAEA,8EAA8E;IAC9E,oEAAoE;IACpE,yEAAyE;IACzE,8EAA8E;IAC9E,uBAAuB;IACvB,MAAMG,YAAYZ,QAAQC,GAAG,CAACY,aAAa,EAAEC,QAAQ,OAAO,IAAI,uBAAuB;;IAEvF,8EAA8E;IAC9E,yEAAyE;IACzE,yEAAyE;IACzE,kFAAkF;IAClF,MAAMC,kBAAkBH,YACpB,CAAC,EAAEI,QAAQ,EAAEC,MAAM,EAAyC,GAC1D;YAACL;YAAWK;YAAQD;SAAS,CAACE,MAAM,CAACC,SAASC,IAAI,CAAC,OACrDC;IAEJ,MAAMC,oBAAwF,CAAC;IAC/F,KAAK,MAAMC,QAAQzB,YAAa;QAC9BwB,iBAAiB,CAACC,KAAK,GAAGR,kBAAkB;YAAEA;QAAgB,IAAI;IACpE;IAEA,OAAOnB,UAAU;QACfG;QACAD,aAAawB;QACbb,QAAQ;YACNe,aAAa;gBAAEnB;gBAAaE;YAAgB;YAC5CJ;YACAsB,QAAQ;YACR,0DAA0D;YAC1DC,gBAAgB;QAClB;IACF;AACF,EAAC"}
+18 -20
View File
@@ -38,32 +38,30 @@ export const buildR2Storage = (collections: string[] = ['media']): Plugin => {
} }
} }
// s3Storage wants Record<string, true> (the literal true, per collection), // Public URL for served media. R2 is private by default; its S3 endpoint only
// not Record<string, boolean>. Object.fromEntries widens true → boolean, so // accepts uploads and won't serve files (403). With a custom domain
// build the map with an explicitly-typed accumulator to keep the literal.
const collectionsConfig: Record<string, true> = {}
for (const slug of collections) {
collectionsConfig[slug] = true
}
// Public URL for served media. R2 is private by default; with a custom domain
// (media.klient.pl → bucket) set R2_PUBLIC_URL so Payload generates URLs // (media.klient.pl → bucket) set R2_PUBLIC_URL so Payload generates URLs
// pointing there instead of the private S3 endpoint (which 403s on the front). // pointing there. Without it, uploads work but images don't display publicly.
// Without it, uploads work but images don't display publicly. See docs/storage.md. // See docs/storage.md.
const publicUrl = process.env.R2_PUBLIC_URL?.replace(/\/$/, '') // strip trailing slash const publicUrl = process.env.R2_PUBLIC_URL?.replace(/\/$/, '') // strip trailing slash
// 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
const collectionsConfig: Record<string, { generateFileURL: typeof generateFileURL } | true> = {}
for (const slug of collections) {
collectionsConfig[slug] = generateFileURL ? { generateFileURL } : true
}
return s3Storage({ return s3Storage({
bucket, bucket,
collections: collectionsConfig, collections: collectionsConfig,
...(publicUrl
? {
// generateFileURL overrides the stored/returned URL to the CDN domain.
// Params come from Payload's storage plugin; type them explicitly since
// the callback shape isn't inferred here (would be implicit any).
generateFileURL: ({ filename, prefix }: { filename: string; prefix?: string }) =>
[publicUrl, prefix, filename].filter(Boolean).join('/'),
}
: {}),
config: { config: {
credentials: { accessKeyId, secretAccessKey }, credentials: { accessKeyId, secretAccessKey },
endpoint, endpoint,