How to add Sanity CDN to next.config.js in Next.js

5 replies
Last updated: May 20, 2024
How would I add Sanity cdn to next.config.js?
AI Update

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.

/** @type {import('next').NextConfig} */
const config = {
  images: {
    remotePatterns: [{ hostname: "<http://cdn.sanity.io|cdn.sanity.io>" }],
  },
};
Thank you.
Per the channel description, use a single thread for your question. Posting it multiple times per day is also not allowed and will result in threads being deleted.
Sorry. I just didn't realise it notified anybody if I posted back in my own thread.
Thanks for understanding.

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.

Was this answer helpful?