Integrating imgix with Next.js
This guide provides instructions on how to integrate imgix with Next.js to handle image optimizations seamlessly. Next.js supports imgix as a custom loader which enables you to leverage imgix’s powerful image processing capabilities directly in your Next.js applications.
Prerequisites
Before integrating imgix with your Next.js project, ensure you have the following:
- A Next.js project setup and running.
- An imgix account and an active source configured.
Configuration
To configure imgix with Next.js, you need to modify the next.config.js
file to include imgix as a custom image loader.
Define the imgix Loader
First, at your project root, create a loader file that specifies how images should be handled by nextjs:
export default function imgixLoader = ({ src, width, quality }) => {
const url = new URL(`https://your-subdomain.imgix.net${src}`)
const params = url.searchParams
params.set("auto", params.getAll("auto").join(",") || "format")
params.set("fit", params.get("fit") || "max")
params.set("w", params.get("w") || width.toString())
return url.href
}
Update the Image Component Configuration
Next, in your next.config.js
file, specify imgix as your custom image loader by updating the images
section:
module.exports = {
images: {
remotePatterns: [
{
protocol: "https",
hostname: "your-subdomain.imgix.net",
},
],
loader: "custom",
loaderFile: "./loader.js",
},
}
Use the Image Component
Now, you can use the Next.js <Image>
component to load images through imgix. Here’s how to implement it in your project:
import Image from "next/image"
const MyImage = () => (
<Image
src="/path/to/image.jpg"
alt="Description of the image"
width={800}
height={600}
sizes="(max-width: 768px) 100vw, 50vw"
/>
)
export default MyImage
Further Reading
For detailed information on configuring image loading in Next.js, refer to the Next.js documentation on the next.config.js
images configuration.