Sanity client fetch returns undefined on Netlify Edge functions

23 replies
Last updated: Jul 12, 2022
šŸ‘‹ Hello, team!
I've been playing around with the sanity-hydrogen-demo.
It works perfectly locally but when I deploy it to Netlify, the sanity client fetch returns
undefined
.
Is there some config I am missing to allow Netlify Edge functions to query Sanity?
It
feels like a CORS problem but I have added the Netlify domain to the Sanity CORS origins for the project.

https://sanity-io-land.slack.com/archives/C9Y51FDGA/p1655916116157169
AI Update

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 requests

Or 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

  1. Deno environment access: In your edge function code, make sure you're accessing environment variables using Deno.env.get() or Netlify.env.get() rather than process.env:
const projectId = Deno.env.get('SANITY_PROJECT_ID');
const dataset = Deno.env.get('SANITY_DATASET');
  1. Sanity client compatibility: The @sanity/client package does support Deno and edge runtimes, so that shouldn't be an issue. Make sure you're using a recent version (v3+).

  2. 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 thread
23 replies
Is your dataset private? If so, maybe once deployed to Netlify it doesn't have access to the correct token?
It is public āœ…
āœ”ļø that shouldn't be the issue then! What does your client configuration look like?
Do you have your projectId defined in
./sanity.config.ts
?This should match the projectId defined in the matching
studio config
sanity.json
(production is the typical dataset name, but this can be changed)

export default {
  apiVersion: 'v2022-05-01',
  dataset: 'production',
  projectId: 'abcd1234', //--- Your unique projectId goes here.
  useCdn: true,
};
It's pretty simple - I don't have a token though. I didn't think I needed one for a public dataset
Yes the project ID definitely matches - I just double checked
I haven’t used this demo config yet and just glazed over the readme. I believe you will need a token for shopify to update documents.
hmm the docs don’t say you need one
I'll add one and let you know how I get on
I’m giving
npx @sanity/cli@shopify init --template shopify
a shot now to see if I can break it too!
Nice thanks!
My help may be limited. This is my first opportunity to touch hydrogen.
To deploy to Netlify, I added this module to vite config btw. Maps hydrogen output to Netlify edge functions

https://github.com/netlify/hydrogen-platform
I’m getting some bugginess with vision and some plugins with my recent v3 beta tinkering and this. I don’t think I’ll be able to have a good response for you today, but I’ll keep tinkering with it.
Unfortunately the token hasn't helped šŸ˜ž
Thanks for your help! I'm in no rush
šŸ™‚ I just found it a little strange because I figured Netlify would be supported which makes me think it's a "me" problem 😁I've also reached out to Netlify to see if they can help .I will keep you updated!
I was hoping on first reply that it might be some low hanging fruit lol.
Here are the netlify integration notes from
hydrogen’s docs : https://docs.netlify.com/integrations/frameworks/hydrogen/
I wouldn’t normally toss a big page of docs at someone unless like in this case, I haven’t had a chance to deploy this myself just yet.
I’ve wanted to use this with a personal project too, and I will try to get a deploy started tomorrow and follow up.
Thanks yea those are the docs I followed šŸ‘

Here's my repo which I took from Sanity's demo and added the Netlify config if you're interested. I also added some i18n functionality.
Side note - the project is awesome, great resource thanks guys
šŸ™‚
Hey
user P
– it’s definitely not a ā€œyouā€ problem!

useSanityQuery
is a wrapper for Hydrogen’s
useQuery
function. Whilst not yet documented on their site,
useQuery
also returns
error
in its response, and tracing this reveals the issue to lie within
@sanity/client
.
I haven’t really delved into this (nor have used Netlify edge functions), but a workaround that works
right now is replacing all instances of
@sanity/client
with
picosanity
(https://github.com/rexxars/picosanity ) which should work just fine, since
useSanityQuery
is only doing basic fetching anyway.
You’ll need to make sure to replace usage in
sitemap.xml.server.ts
too, since that is also fetching your Sanity dataset to generate a sitemap at runtime.
(We’ll be updating that demo soon with support for basic account creation / management as well, if that’s of interest)
Oh thanks
user F
! That all makes total sense.Will switch
@sanity/client
over to
picosanity
šŸ‘
user F
user U
user M
Just wanted to confirm that switching to
picosanity
has worked šŸ‘
Thanks for your help!

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?