NextJS Image component setup with Sanity CDN in next.config.js
Great questions! Let me help you with both of these Next.js image configuration issues.
Should you use Next.js <Image/> instead of <img/>?
Yes, absolutely! ESLint is right to flag this. The Next.js Image component is highly recommended because it:
- Automatically optimizes images (lazy loading, responsive sizes, modern formats like WebP)
- Prevents layout shift with automatic sizing
- Improves performance and Core Web Vitals scores
- Works great with Sanity's image CDN
When you're using images from Sanity, you'll typically use the @sanity/image-url package to generate the URLs, then pass them to Next.js Image.
Configuring next.config.js properly
You're on the right track, but the configuration syntax depends on your Next.js version. Here's how to combine everything properly:
For Next.js 12.3+ (using remotePatterns - recommended):
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'cdn.sanity.io',
},
],
},
// ... any other config options
}
module.exports = nextConfigFor older Next.js versions (using domains):
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
domains: ['cdn.sanity.io'],
},
// ... any other config options
}
module.exports = nextConfigThe key point: nextConfig is just an object that holds all your configuration. You're adding the images property to that object, then exporting it. Don't remove = nextConfig - you're defining the config object first, then exporting it.
Quick example of using Sanity images with Next.js Image:
import Image from 'next/image'
import imageUrlBuilder from '@sanity/image-url'
const builder = imageUrlBuilder(client)
function urlFor(source) {
return builder.image(source)
}
// In your component:
<Image
src={urlFor(post.mainImage).width(800).url()}
alt={post.mainImage.alt}
width={800}
height={600}
/>Note: Make sure the URL you're passing to <Image> uses https:// (not http://) and points to cdn.sanity.io. The tutorial you're following should have examples of this pattern!
Show original thread2 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.