How to optimize images that are external?

Hi. I'm using this code
const normalizeSrc = (src: string) => {
return src.startsWith("/") ? src.slice(1) : src;
};

export default function cloudflareLoader({
src,
width,
quality,
}: { src: string; width: number; quality?: number }) {
if (process.env.NODE_ENV === "development") {
return src;
}
const params = [`width=${width}`];
if (quality) {
params.push(`quality=${quality}`);
}
const paramsString = params.join(",");

return `/cgi/image/${paramsString}/${normalizeSrc(src)}
}
const normalizeSrc = (src: string) => {
return src.startsWith("/") ? src.slice(1) : src;
};

export default function cloudflareLoader({
src,
width,
quality,
}: { src: string; width: number; quality?: number }) {
if (process.env.NODE_ENV === "development") {
return src;
}
const params = [`width=${width}`];
if (quality) {
params.push(`quality=${quality}`);
}
const paramsString = params.join(",");

return `/cgi/image/${paramsString}/${normalizeSrc(src)}
}
besides my local images from the public directory in next.js, i have a dynamic page where the images are coming from a different source https://data.companyname.com/ppic/test.jpeg how can i use this in image in the custom loader and optimize it? at the moment they are not loading at all thanks
2 Replies
LeftyLlama
LeftyLlama2w ago
I don't think this is possible by modifying the URL alone, but it should be doable by having your worker actually request the image using fetch, as documented here: https://developers.cloudflare.com/images/transform-images/transform-via-workers/#an-example-worker
Cloudflare Docs
Transform via Workers · Cloudflare Images docs
Using Cloudflare Workers to transform with a custom URL scheme gives you powerful programmatic control over every image request.
Rohil
RohilOP2w ago
oh okay i will take a look thank you

Did you find this page helpful?