How to add Sanity CDN to next.config.js in Next.js
To add the Sanity CDN to your next.config.js (or next.config.ts), you need to configure the images section with remotePatterns to allow Next.js to load images from Sanity's CDN. Here's how:
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'cdn.sanity.io',
},
],
},
};
module.exports = nextConfig;Or if you're using TypeScript:
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
images: {
remotePatterns: [
{ protocol: 'https', hostname: 'cdn.sanity.io' },
],
},
};
export default nextConfig;This configuration tells Next.js that it's safe to load and optimize images from cdn.sanity.io when using the Next.js <Image> component.
Once configured, you can use images from Sanity with the Next.js Image component along with @sanity/image-url to build optimized image URLs:
import Image from 'next/image';
import { urlFor } from './lib/image'; // your urlFor helper
<Image
src={urlFor(post.mainImage).url()}
alt={post.mainImage.alt}
width={800}
height={600}
/>The remotePatterns approach is the modern way to configure external image domains in Next.js (replacing the older domains configuration). You can also be more specific by adding pathname restrictions if needed, but the basic configuration above is what you need to get Sanity's CDN working with Next.js images.
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.