Sanity client fetch returns undefined on Netlify Edge functions
Based on the error you're describing, this is most likely not a CORS issue but rather an environment variables problem specific to how Netlify Edge Functions work.
Netlify Edge Functions run on Deno (not Node.js), and they have a different way of handling environment variables compared to regular Netlify Functions or local development. Here's what's likely happening:
The Problem
When your Sanity client is returning undefined, it's probably because the client isn't being initialized properly due to missing environment variables. In Netlify Edge Functions, environment variables need to be explicitly exposed in your netlify.toml configuration file.
The Solution
In your netlify.toml file, you need to add an [edge_functions] section that explicitly declares which environment variables should be available to your edge functions:
[edge_functions]
# Expose your Sanity environment variables
[edge_functions.config]
SANITY_PROJECT_ID = "your-project-id"
SANITY_DATASET = "production"
SANITY_API_TOKEN = "your-token" # if using authenticated requestsOr if you want to expose all environment variables to a specific edge function:
[[edge_functions]] function = "your-function-name" path = "/your-path" [edge_functions.config] # List your environment variables here environment = ["SANITY_PROJECT_ID", "SANITY_DATASET", "SANITY_API_TOKEN"]
Additional Considerations
- Deno environment access: In your edge function code, make sure you're accessing environment variables using
Deno.env.get()orNetlify.env.get()rather thanprocess.env:
const projectId = Deno.env.get('SANITY_PROJECT_ID');
const dataset = Deno.env.get('SANITY_DATASET');Sanity client compatibility: The
@sanity/clientpackage does support Deno and edge runtimes, so that shouldn't be an issue. Make sure you're using a recent version (v3+).Check your client initialization: Verify that your Sanity client is being initialized with the correct configuration:
import {createClient} from '@sanity/client'
const client = createClient({
projectId: Deno.env.get('SANITY_PROJECT_ID'),
dataset: Deno.env.get('SANITY_DATASET'),
useCdn: true,
apiVersion: '2024-01-01'
})CORS settings in your Sanity project are important, but they would typically throw a CORS error rather than returning undefined. The undefined response strongly suggests the client isn't being created or configured correctly due to missing environment variables.
After updating your netlify.toml, redeploy your site and the edge functions should have access to the necessary environment variables to properly initialize the Sanity client.
Show original thread23 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.