Write a custom next/image loader that serves every picture from the shop's image CDN
Leaf and Kettle's photos are served by an image CDN at https://images.leafandkettle.example, which resizes and converts images itself. next.config.ts already tells next/image to use image-loader.ts instead of Next.js's own optimizer. Write that file. Its default export gets { src, width, quality } for each URL next/image puts in an <img>, and returns that URL.
A path on the shop, like /teas/mint.jpg, has the same path on the CDN, with width, quality, and format=auto added to its query, in that order. quality is undefined when the <Image> doesn't set one: use 75 then. Keep any query the path already has, like ?v=3.
A photo from another site, like a partner farm's, goes through the CDN's /fetch endpoint, with its full address in the url param, then the same three params. A photo that's already on the CDN is treated like a path on the shop: its own path and query, plus the three params.
imageLoader({ src: "/teas/mint.jpg", width: 640 });
// "https://images.leafandkettle.example/teas/mint.jpg?width=640&quality=75&format=auto"
imageLoader({ src: "https://farm.example/oolong.jpg", width: 750, quality: 50 });
// "https://images.leafandkettle.example/fetch?url=https%3A%2F%2Ffarm.example%2Foolong.jpg&width=750&quality=50&format=auto"
image-loader.tsimport type { ImageLoaderProps } from "next/image";
const CDN = "https://images.leafandkettle.example";
export default function imageLoader({ src }: ImageLoaderProps) {
return CDN + src;
}
next.config.ts (read-only)import type { NextConfig } from "next";
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
images: {
loader: "custom",
loaderFile: "./image-loader.ts",
},
};
export default nextConfig;
- a path on the shop gets the CDN's address, the width, quality 75, and format=auto
- uses the quality the image asks for
- gives every width a srcset can ask for a URL of its own
- keeps the query string the path already has
- sends another site's photo through /fetch, with its whole address encoded
- doesn't send the CDN's own photos through /fetch
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…