Mark Ku's Blog

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

Link

Enable Image Resizing in Cloudflare

Link

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>

Author

Mark Ku

擁有 10+ 年經驗的資深軟體工程師,現為 AI 應用 Builder,專注於大型平台架構與簡化複雜系統設計,從電商系統到訂閱與收費平台,結合 AI Agent、AI 整合與自動化開發,打造高效率且可持續演進的產品技術基礎。Read More

Found this useful?

The author's free tools, daily podcasts and newsletter are all here.

Mark Ku · This article is licensed under CC BY 4.0. Credit the author and link back to the original when reusing it.

Comments

Subscribe to Newsletter

Subscribe to get new posts delivered instantly — never miss a tech share.

By submitting, you agree to receive emails. You can anytime.

Popular Posts

View all
Mark Ku
··602

Oracle Cloud Always Free Tier: Linux Host and Static IP for a $0 Cloud Solution

Oracle Cloud Always Free Tier: Linux Host and Static IP for a $0 Cloud Solution
Mark Ku
··492

Say Goodbye to Postman's Fee Trap! A Hands-on Guide to Bruno, the Open-Source Git-Native API Testing Powerhouse.

Say Goodbye to Postman's Fee Trap! A Hands-on Guide to Bruno, the Open-Source Git-Native API Testing Powerhouse.
Mark Ku
··334

A Free, Open-Source, Notion-like Knowledge Base — A Complete Guide to Deploying and Backing Up Outline Wiki

A Free, Open-Source, Notion-like Knowledge Base — A Complete Guide to Deploying and Backing Up Outline Wiki
Mark Ku
··268

Training Your Own AI Voice: Hardware Requirements, Open-Source Model Comparison, and LoRA Fine-Tuning

Training Your Own AI Voice: Hardware Requirements, Open-Source Model Comparison, and LoRA Fine-Tuning
Mark Ku
··218

Building an Efficient API Management Platform: Deploying Kong Gateway from Scratch - Part 1

Building an Efficient API Management Platform: Deploying Kong Gateway from Scratch - Part 1
Mark Ku
··217

Setting Up Samba on Ubuntu to Share Folders with Windows 11

Setting Up Samba on Ubuntu to Share Folders with Windows 11
Custom NextJS image loader with cloudflare - Mark Ku's Tech Notes