Skip to content

Instantly share code, notes, and snippets.

@GregBrimble
Created September 27, 2021 09:41
Show Gist options
  • Save GregBrimble/01934d08de1af90c518632b4bb54a707 to your computer and use it in GitHub Desktop.
Save GregBrimble/01934d08de1af90c518632b4bb54a707 to your computer and use it in GitHub Desktop.
Example of Cloudflare Images on Next.js (WIP)
import Image, { ImageLoader } from "next/image";
type Width = [string, number];
const widths = {
sm: 640,
md: 768,
lg: 1024,
xl: 1280,
};
const sortedWidths: Width[] = Object.entries(widths).sort(
(a, b) => a[1] - b[1]
);
const largestWidth: Width = sortedWidths[sortedWidths.length - 1];
/*
* Accepts an Cloudflare Images image ID (`src`) and width (`width`)
* Returns a URL for the next-size-up image variant (with a fallback to the largest)
*/
const cloudflareImagesLoader: ImageLoader = ({ src, width }) => {
// Note that `width` might be larger than you're expecting because of a device pixel ratio (DPR)
const [variantName] =
sortedWidths.find(([variantName, value]) => width <= value) || largestWidth;
// Next.js expects to see the width somewhere in the URL,
// so we add the no-op `width` query parameter to suppress the warning
// https://nextjs.org/docs/messages/next-image-missing-loader-width
return `https://imagedelivery.net/Hd6PfXQgWuxwOTKaoptnYw/${src}/${variantName}?width=${width}`;
};
export default function ImageTest() {
return (
<div>
<h1>Image Test</h1>
<Image
src="c367d2f5-da91-431f-ea3b-dce0d41fd500"
loader={cloudflareImagesLoader}
width={380}
height={760}
/>
</div>
);
}
module.exports = {
images: {
loader: "custom",
imageSizes: [640, 768, 1024, 1280],
deviceSizes: [640, 768, 1024, 1280],
domains: ["imagedelivery.net"],
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment