Sanity ClientError: Unauthorized in Netlify function (production only)
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:
Token not properly passed to the client - Double-check that your environment variable is correctly set in Netlify's production environment (not just locally). In Netlify's dashboard, go to Site settings > Environment variables and verify
SANITY_API_TOKENexists and matches your token from manage.sanity.io.Token permissions - Ensure your API token has the appropriate role assigned. If you're just reading content, a "Viewer" role token should work. For writes, you'll need "Editor" or a custom role with appropriate permissions.
Token format issues - Make sure you're passing the token exactly as created, with no extra spaces or quotes accidentally included from your environment variable.
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:
- Verify your environment variable is set in Netlify's production environment
- Confirm the token has the right permissions in manage.sanity.io (Settings > API > Tokens)
- Try creating a fresh token if the current one might be corrupted
- Remove the CORS origin configuration since it's not relevant for serverless functions
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 thread3 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.