Custom NextJS image loader with cloudflare
Problem
Our Next.js application occasionally becomes overloaded. When it cannot keep up with rendering demand, users receive stale pages instead of fresh content.
Solution Concept
To reduce the load on Next.js and optimize image delivery, we plan to swap the default Next.js image loader for the Cloudflare Image Resizing API.
Cloudflare Image Resizing Documentation
Enable Image Resizing in Cloudflare
Create a Function for Image Optimization
import { ImageLoaderProps } from 'next/image';
export const contentDomain = 'https://content.letgo.com.tw/';
const normalizeSrc = (src: string) => {
return src.startsWith('/') ? src.slice(1) : src;
};
export const cloudflareLoader = ({ src, width, quality = 75 }: ImageLoaderProps) => {
const params = [`width=${width}`, 'format=auto'];
if (quality) {
params.push(`quality=${quality}`);
}
const paramsString = params.join(',');
return `${$contentDomain}cdn-cgi/image/${paramsString}/${normalizeSrc(src)}`;
};
export const getCloudflareImageUrl = (
src?: string,
width?: number,
height?: number,
quality?: number,
fit?: string,
options?: string[]
) => {
const params: string[] = ['format=auto'];
// todo default image
if (!src) {
return;
}
quality = quality || 75;
if (width) {
params.push(`width=${width}`);
}
if (height) {
params.push(`height=${height}`);
}
if (fit) {
params.push(`fit=${fit}`);
}
if (quality) {
params.push(`quality=${quality}`);
}
if (options) {
params.push(...options);
}
const paramsString = params.join(',');
return `${contentDomain}cdn-cgi/image/${paramsString}/${normalizeSrc(src)}`;
};
Usage
Specify the Next.js Image Loader
It is recommended to use the Next.js Image component — it provides a better user experience on your website.
<Image
loader={cloudflareLoader}
src={`${$projects.content}${item.Image}`}
width={175}
height={175}
alt={'promo image'}
></Image>
Alternative Usage: Call getCloudflareImageUrl to get an optimized image URL
<div style={{ backgroundImage: `url("${getCloudflareImageUrl(contentURL + communityJson.Content.Image)}")` }} >
</div>





























Comments