Discrepancy between local and production image URLs with @sanity/image-url
The issue you're experiencing is almost certainly related to how environment variables are configured in Gatsby Cloud versus your local environment. The undefined/undefined in your image URLs indicates that process.env.PROJECT_ID and process.env.DATASET aren't being read correctly in production.
Here are the key things to check and fix:
1. Environment Variable Naming in Gatsby
Gatsby has specific requirements for environment variables. Variables that need to be available in browser-side code (which includes your image URL builder) must be prefixed with GATSBY_.
In Gatsby Cloud, update your environment variables to:
GATSBY_PROJECT_IDinstead ofPROJECT_IDGATSBY_DATASETinstead ofDATASETGATSBY_API_VERSIONinstead ofAPI_VERSION
Then update your config.js:
const Config = {
source: {
projectId: process.env.GATSBY_PROJECT_ID,
dataset: process.env.GATSBY_DATASET,
apiVersion: process.env.GATSBY_API_VERSION,
},
}
module.exports = Config2. Verify Variables are Set in Gatsby Cloud
Make sure you've actually added these environment variables in your Gatsby Cloud project settings. Go to your site settings → Environment Variables and add them there with the correct values.
3. Why it Works Locally
Locally, you might be using a .env file or have these variables set in your shell environment, which is why it works. But Gatsby Cloud needs them explicitly configured in its dashboard.
4. Rebuild After Adding Variables
After adding or changing environment variables in Gatsby Cloud, you need to trigger a new build for them to take effect.
Alternative Approach
If you prefer to hardcode non-sensitive values (project ID and dataset are public information in Sanity), you could also just set them directly:
const Config = {
source: {
projectId: 'your-project-id',
dataset: 'production',
apiVersion: '2023-05-03',
},
}This is actually a common pattern since these values aren't secrets - they're already exposed in your frontend code and API requests anyway.
The GATSBY_ prefix requirement is the most likely culprit here. Make that change and redeploy, and your images should work correctly in production.
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.