My Image URLs Are Breaking When Deploying to Netlify
I can help you troubleshoot this image URL issue with Netlify deployment. This is a common problem that usually relates to how environment variables or client configuration is handled between local and production environments.
The most common causes when using @sanity/image-url are:
1. Environment Variables Not Set in Netlify
Your Sanity client configuration needs the correct projectId and dataset in production. Make sure you've added these as environment variables in your Netlify dashboard (Site settings → Environment variables):
SANITY_PROJECT_ID=your-project-id SANITY_DATASET=production
Then ensure your client configuration is reading from these variables:
import { createClient } from '@sanity/client'
export const client = createClient({
projectId: process.env.SANITY_PROJECT_ID || process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
dataset: process.env.SANITY_DATASET || process.env.NEXT_PUBLIC_SANITY_DATASET,
useCdn: true,
apiVersion: '2024-01-01'
})2. Client-Side vs Server-Side Environment Variables
If you're using a framework like Next.js, remember that client-side code needs variables prefixed with NEXT_PUBLIC_. If your imageUrlBuilder is running in the browser, use:
NEXT_PUBLIC_SANITY_PROJECT_IDNEXT_PUBLIC_SANITY_DATASET
3. Build-Time vs Runtime Variables
Netlify needs to have these variables set before the build runs if they're being bundled into your code. Check that you've:
- Set the environment variables in Netlify
- Triggered a new deploy after setting them (old builds won't have the new variables)
4. Check Your Image Domain Configuration
According to the @sanity/image-url documentation, if you're using Next.js, ensure your next.config.js allows Sanity's CDN:
module.exports = {
images: {
remotePatterns: [
{ protocol: 'https', hostname: 'cdn.sanity.io' }
]
}
}Quick Debug Steps:
- Console log your client configuration in production to verify the projectId and dataset are correct
- Check the Network tab in your browser to see the actual URL being requested
- Verify the URL structure matches:
https://cdn.sanity.io/images/{projectId}/{dataset}/...
The broken request you're seeing is likely generating a malformed URL because the projectId or dataset is undefined in your production build. Setting the environment variables properly in Netlify should resolve this!
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.