Mark Ku's Blog
首頁 關於我
Custom NextJS image loader with cloudflare
Frontend
Custom NextJS image loader with cloudflare
Mark Ku
Mark Ku
November 11, 2022
1 min

Custom NextJS image loader with cloudflare

Problem

Our NextJS Application are occasionally overloaded. Cause not catch-up rendering then get old pages.

Solution concept

For reduce NEXT JS load and optimize images, We plan change Next JS Image loader to Cloudfalre resize api

Cloudfalre image resizing document

Link

Enable image-resizing in cloudfalre

Link

create a fuction 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)}`;
};

Useage

Specify the NextJS image loader

It is recommended to use NextJS image in Next. it will make better experience on our website.

   <Image
    loader={cloudflareLoader}
    src={`${$projects.content}${item.Image}`}
    width={175}
    height={175}
    alt={'promo image'}
    ></Image>

Another useage. You can call the getCloudflareImageUrl method to get the optimized image url

<div style={{ backgroundImage: `url("${getCloudflareImageUrl(contentURL + communityJson.Content.Image)}")` }} >
</div>

Tags

Mark Ku

Mark Ku

Software Developer

9年以上豐富網站開發經驗,開發過各種網站,電子商務、平台網站、直播系統、POS系統、SEO 優化、金流串接、AI 串接,Infra 出身,帶過幾次團隊,也加入過大團隊一起開發。

Expertise

前端(React)
後端(C#)
網路管理
DevOps
溝通
領導

Social Media

facebook github website

Related Posts

這些年對 Next.JS 做過的網站效能優化
這些年對 Next.JS 做過的網站效能優化
October 10, 2024
1 min

Quick Links

關於我

Social Media