Integrate with frameworks
Image transformations can be used automatically with the Next.js <Image />
component ↗.
To use image transformations, define a global image loader or multiple custom loaders for each <Image />
component.
Next.js will request the image with the correct parameters for width and quality.
Image transformations will be responsible for caching and serving an optimal format to the client.
To use Images with all your app's images, define a global loaderFile ↗ for your app.
Add the following settings to the next.config.js file located at the root our your Next.js application.
module.exports = { images: { loader: 'custom', loaderFile: './imageLoader.ts', },}
Next, create the imageLoader.ts
file in the specified path (relative to the root of your Next.js application).
const normalizeSrc = (src: string) => { return src.startsWith("/") ? src.slice(1) : src;};
export default function cloudflareLoader({ src, width, quality,}: { src: string; width: number; quality?: number }) { if (process.env.NODE_ENV === "development") { return src; } const params = [`width=${width}`]; if (quality) { params.push(`quality=${quality}`); } const paramsString = params.join(","); return `/cdn-cgi/image/${paramsString}/${normalizeSrc(src)}`;}
Alternatively, define a loader for each <Image />
component.
import Image from 'next/image';
const normalizeSrc = src => { return src.startsWith('/') ? src.slice(1) : src;};
const cloudflareLoader = ({ src, width, quality }) => { if (process.env.NODE_ENV === "development") { return src; } const params = [`width=${width}`]; if (quality) { params.push(`quality=${quality}`); } const paramsString = params.join(','); return `/cdn-cgi/image/${paramsString}/${normalizeSrc(src)}`;};
const MyImage = props => { return ( <Image loader={cloudflareLoader} src="/me.png" alt="Picture of the author" width={500} height={500} /> );};