Sanity Pioneers: Get early access to betas, extra AI credits, and a direct line to the engineering team. Apply now

Sanity ClientError: Unauthorized in Netlify function (production only)

3 repliesLast updated: Dec 1, 2025

Hey guys, I'm trying to use the
@sanity/client
package from a Netlify function but am getting an error only in production, not locally with netlify dev:
Sanity error: ClientError: Unauthorized - Session not found

I've created an API token and am passing it with the sanity client calls, so think that the error may have something to do with my CORS Origins configuration? I allowed credentials for a netlify domain like
<https://bloopity-blopity-1n23io.netlify.app>
does that look right? Any help would be much appreciated!
AI Update

I understand the frustration - "Session not found" errors can be confusing! The good news is this has nothing to do with your CORS configuration.

CORS doesn't apply to serverless functions like Netlify Functions. CORS Origins only control browser-based requests where the browser enforces cross-origin security. Since your Netlify function runs server-side, not in a browser, CORS settings don't affect it at all. You can safely remove that Netlify domain from your CORS origins in manage.sanity.io (Settings > API > CORS Origins) - it's not needed for function-to-Sanity communication.

Common causes of "Session not found" errors with API tokens:

Debugging steps:

import {createClient} from '@sanity/client'

const client = createClient({
  projectId: 'your-project-id',
  dataset: 'your-dataset',
  token: process.env.SANITY_API_TOKEN,
  apiVersion: '2024-01-01'
})

// Add logging to verify token is present (but don't log the actual token value!)
console.log('Token exists:', !!process.env.SANITY_API_TOKEN)

Why it works locally but not in production:

The most common reason is that netlify dev uses your local .env file, while production Netlify uses environment variables configured in their dashboard. These are separate configurations that need to be set independently.

Next steps:

If you're still stuck after checking these, let us know what the token permissions are set to and whether the environment variable shows up in your Netlify build logs (just the existence, not the value!).

Show original thread
3 replies

Was this answer helpful?

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.

Related contributions