Hi everyone! 👋
I'm experiencing slow image loading on my site with the following setup:
- Payload CMS
- @payloadcms/plugin-cloud-storage with R2 (Cloudflare Storage)
- Vercel for deployment
- Neon for PostgreSQL database
- Using S3 compatibility for R2
- Images are served through Payload's
/api/mediaendpoint
- Deployed on Vercel with Edge Network
Images are taking a long time to load, even though I'm using Cloudflare R2 for storage.
Has anyone found a good solution to optimize image loading times with this setup? Maybe using Cloudflare CDN or other optimizations?
Thanks in advance for any help! 🙏
I've used r2 + cloudflare CDN by setting up a subdomain with the bucket
and no image optimisation via vercel
payload.config.ts has this
s3Storage({
collections: {
media: {
prefix: 'media/c',
disableLocalStorage: true,
},
},
bucket: process.env?.R2_BUCKET || '',
config: {
endpoint: process.env?.R2_ENDPOINT || '',
credentials: {
accessKeyId: process.env?.R2_ACCESS_KEY_ID || '',
secretAccessKey: process.env?.R2_SECRET_ACCESS_KEY || '',
},
region: 'auto',
},
}),Oh ty ! I will try !
The image is hosted on a CDN, so you don't need to call yourdomain.com/api/media to get the CDN URL. The solution is to replace all images in the content before returning it to the client. Use the afterRead hook. For me, I convert the lexical content to HTML and then replace all /api/media with cdn.domain.com/media/....
export const afterReadHook: CollectionAfterReadHook<Resource> = async (args) => {
const { context, doc, req, collection } = args;
const richTextField: RichTextField = collection.fields.find(
(field) => 'name' in field && field.name === 'content',
) as RichTextField;
const lexicalAdapter: LexicalRichTextAdapter = richTextField.editor as LexicalRichTextAdapter;
const sanitizedServerEditorConfig: SanitizedServerEditorConfig = lexicalAdapter.editorConfig;
if (doc.content) {
const html = await LexicalHelper.convertLexicalToHTML(
doc.content,
{
req,
payload: req.payload,
}
);
// replace all media url in contentHtml with cdn url
doc.contentHtml = replaceMediaUrlWithCdnUrl(html);
//doc.contentHtml = html;
console.log(doc.contentHtml);
}
return doc;
};You alright ty so much !
works like that
great, I don't know that option
hotspot
Star
Discord
online
Get dedicated engineering support directly from the Payload team.