Issue with 401 Unauthorized error during build process on Vercel
I understand you're getting a 401 Unauthorized error during your Vercel build! This is a common authentication issue with Sanity projects. While you mentioned the full error message is in the thread below, I can help you troubleshoot the most likely causes.
A 401 error typically means Sanity can't authenticate your request, usually due to missing or incorrect API tokens. Here are the most common culprits:
Check Your Environment Variables
The most frequent cause is missing or incorrectly configured API tokens in your Vercel environment variables:
Verify the token exists in Vercel: Go to your Vercel project settings → Environment Variables. Make sure you have your Sanity token set (commonly named
SANITY_API_TOKEN,SANITY_API_READ_TOKEN, orNEXT_PUBLIC_SANITY_TOKENdepending on your setup).Check which environments it's enabled for: Ensure the token is enabled for "Production" (and "Preview" if needed), not just "Development".
Redeploy after adding variables: If you just added the environment variable, you need to trigger a new deployment for it to take effect.
Generate the Correct Token
If you need to create or verify your token:
Run
npx sanity@latest managefrom your project directory, or access Manage from your Studio menuNavigate to the API tab
Create a new token with appropriate permissions:
- For read-only access (most frontend builds): use Viewer permissions
- For preview/draft content: you'll need at least Viewer permissions on the appropriate dataset
Copy the token and add it to your Vercel environment variables
Common Token Issues
- Using a personal token instead of a robot token: For production builds, use robot tokens rather than personal tokens
- Token doesn't have access to the dataset: Make sure the token has permissions for the dataset you're querying (usually
production) - Accessing draft content without authentication: If you're using perspectives like
previewDraftsor querying draft documents, you must include a valid token - Token stored incorrectly: Store tokens in environment variables, never hardcode them in your code
Variable Naming
Double-check that your code is looking for the same environment variable name you've set in Vercel. If your code expects SANITY_API_READ_TOKEN but Vercel has SANITY_API_TOKEN, they won't match.
If you can share the specific error message or relevant parts of your build logs, I (or others in the community) can provide more targeted help! Look especially for lines mentioning "401", "unauthorized", or "authentication".
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.