Issue with 401 Unauthorized error during build process on Vercel

27 replies
Last updated: May 3, 2024
Hello everyone,
I'm currently facing an issue during my build process on Vercel: a 401 Unauthorized error code. Despite my best efforts, i can't seem to figure out what's wrong. The error message is quite lengthy, and I'm unsure which part is most relevant to resolving this issue. I'll leave the error-message down below in this thread. I would greatly appreciate it if someone could take a moment to review it
😃
AI Update

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:

  1. 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, or NEXT_PUBLIC_SANITY_TOKEN depending on your setup).

  2. Check which environments it's enabled for: Ensure the token is enabled for "Production" (and "Preview" if needed), not just "Development".

  3. 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:

  1. Run npx sanity@latest manage from your project directory, or access Manage from your Studio menu

  2. Navigate to the API tab

  3. 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
  4. 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 previewDrafts or 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".

 Generating static pages (5/11) 
eU [Error]: Unauthorized - Session not found
    at onResponse (/vercel/path0/.next/server/chunks/919.js:10:502)
    at /vercel/path0/.next/server/chunks/919.js:1:116054
    at n (/vercel/path0/.next/server/chunks/919.js:2:2623)
    at /vercel/path0/.next/server/chunks/919.js:2:3070
    at /vercel/path0/.next/server/chunks/919.js:2:1406
    at P.s.onreadystatechange (/vercel/path0/.next/server/chunks/919.js:2:1609)
    at /vercel/path0/.next/server/chunks/919.js:2:190
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  statusCode: 401,
  response: {
    body: {
      errorCode: 'SIO-401-ANF',
      error: 'Unauthorized',
      message: 'Session not found',
      statusCode: 401
    },
    url: '<https://xxxxxxxx.api.sanity.io/v2023-01-07/data/query/production?query=%0A*%5B_type+%3D%3D+%22bedriftSchema%22+%26%26+slug.current+%3D%3D+%22bedrift%22%5D%5B0%5D%7B%0A++title%2C%0A+++slug%2C%0A++hero%7B%0A++++title%2C%0A++++description%2C%0A++++%22heroImageUrl%22%3A+heroImage.image.asset-%3Eurl%2C+%0A++++%22overlayOpacity%22%3A+heroImage.overlayOpacity%2C%0A++++%22overlayColor%22%3A+heroImage.overlayColor%2C+%0A++++%22linkText%22%3A+paameldingseLenke.linkText%2C%0A++++%22linkHref%22%3A+paameldingseLenke.linkHref%2C%0A++++%22logoUrl%22%3A+logo.asset-%3Eurl%2C%0A++++opptaksInfo%0A%0A++%7D%2C%0A++pageBuilder%5B%5D%7B%0A++++%0A++_type%2C%0A++_type+%3D%3D+%27bildeMedTekst%27+%3D%3E+%7B%0A++++heading%2C%0A++++excerpt%2C%0A++++image%7B%0A++++++alt%2C%0A++++++%22imageUrl%22%3A+asset-%3Eurl%0A++++%7D%2C%0A++++%22bildeMedTekstLenke%22%3A+%7B%0A++++++%22lenke%22%3A+bildeMedTekstLenke.lenke%2C%0A++++++%22lenketekst%22%3A+bildeMedTekstLenke.lenketekst%0A++++%7D%0A++%7D%2C%0A++_type+%3D%3D+%27tekst%27+%3D%3E+%7B%0A++++tittel%2C%0A++++innhold%0A++%7D%2C%0A++_type+%3D%3D+%27arrangementKortGruppe%27+%3D%3E+%7B%0A++++tittel%2C%0A++++undertittel%0A++%7D%2C%0A++_type+%3D%3D+%27tidligereArrangementGruppe%27+%3D%3E+%7B%0A++++tittel%2C%0A++%7D%2C%0A++_type+%3D%3D+%27samarbeidsPartnere%27+%3D%3E+%7B%0A++++tittel%2C%0A++++karusellBilder%5B%5D%7B%0A++++++%22imageUrl%22%3A+asset-%3Eurl%2C%0A++++%7D%0A++%7D%2C%0A++_type+%3D%3D+%27infoKortGruppe%27+%3D%3E+%7B%0A++++_key%2C%0A++++title%2C%0A++++%22cards%22%3A+cards%5B%5D%7B%0A++++++_type%2C%0A++++++_id%2C%0A++++++title%2C%0A++++++time%2C%0A++++++location%2C%0A++++++description%2C%0A++++++%22icon%22%3A+%7B%0A++++++++name%2C%0A++++++++provider%2C%0A++++++++%22svg%22%3A+icon.svg+%2F%2F+Henter+SVG-dataen%0A++++++%7D%0A++++%7D%0A++%7D%2C%0A++_type+%3D%3D+%27paamelding%27+%3D%3E+%7B%0A++++title%2C%0A++++%22paameldingsId%22%3A+paameldingsId.current%2C%0A++++%22paameldingsknapper%22%3A+paameldingsknapper%5B%5D%7B%0A++++++tekst%2C%0A++++++%22knappTekst%22%3A+knappTekst%2C%0A++++++%22lenke%22%3A+lenke%0A++++%7D%0A++%7D%0A%0A++%7D%0A%7D&%24slug=%22bedrift%22&perspective=published>',
    method: 'GET',
    headers: {
      'alt-svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000',
      'content-length': '97',
      'content-type': 'application/json; charset=utf-8',
      date: 'Tue, 19 Mar 2024 19:25:07 GMT',
      'strict-transport-security': 'max-age=63072000; includeSubDomains; preload',
      vary: 'origin',
      via: '1.1 google',
      xkey: 'project-xxxxxxxx'
    },
    statusCode: 401,
    statusMessage: 'Unauthorized'
  },
  responseBody: '{\n' +
    '  "errorCode": "SIO-401-ANF",\n' +
    '  "error": "Unauthorized",\n' +
    '  "message": "Session not found",\n' +
    '  "statusCode": 401\n' +
    '}',
  details: undefined
Have you added Vercel to your allowed CORS origins in sanity.io/manage ?
Yup. My page is live, deployed on Vercel. I’ve been doing quite a bit of reworking on the page implementing visual editing 😋, and the upgraded code gets this error. I haven’t touched Vercel since the initial configuration for when I first deployed the old version 🤔
According to the docs , "Unauthorized - Session not found" could mean 1 of 4 things:
    - A temporary issue, please try to run your command again.
    - You have specified an invalid token with the SANITY_AUTH_TOKEN env variable.
    - The session timed out. Try to log out and log in again with the sanity logout and sanity login CLI commands.
    - There was an issue with your logged in user. Try to logout and login again.
I've been getting this error message
for a week now and am stuck because it's so non-specific
Hm, figured out what your issue is yet?
I've tried updating sanity/cli to ^3.35.1", and then running sanity login, but i still get the same error in vercel. These are the variables i have in my .env file, am i missing something?
NEXT_PUBLIC_SANITY_PROJECT_ID
NEXT_PUBLIC_SANITY_DATASET
NEXT_PUBLIC_SANITY_API_VERSION
SANITY_API_READ_TOKEN
SANITY_API_EDITOR_TOKEN
Did you add your vars to your vercel project?
Yes, i think this looks correct?
Do i have to add NEXT_PUBLIC in the two top variables?
You don’t want tokens to be public. Is your Studio embedded in your Next app or is it separate?
Yeah thats's what i tought heh. It's embedded
Can you try adding NEXT_PRIVATE before them?
I tried that, but i still got the same error 😞
Can you share how you’ve configured your client and the code for wherever you’re firing off that query?
Yes, i think this is it. This query is also used in the preview component:
//sanity.client.ts
import {createClient} from '@sanity/client/stega'

export const projectId = process.env.NEXT_PUBLIC_SANITY_PROJECT_ID
export const dataset = process.env.NEXT_PUBLIC_SANITY_DATASET
const apiVersion = process.env.NEXT_PUBLIC_SANITY_API_VERSION

export const client = createClient({
  projectId,
  dataset,
  apiVersion,
  useCdn: false,
  perspective: 'published',
  stega: {
    enabled: false,
    studioUrl: '/studio',
  },
})

// C:\Users\mariu\start\hjemmeside\app\(user)\bedrift\page.tsx
import BedriftPreview from '@/components/siderPreview/BedriftPreview'
import Bedrift from '@/components/sider/BedriftSide'
import {draftMode} from 'next/headers'
import {notFound} from 'next/navigation'
import {SanityDocument} from '@sanity/client'
import {loadQuery} from '@/sanity/lib/store'
import {Metadata} from 'next'

import {BEDRIFT_QUERY} from '@/sanity/lib/queries'

export const metadata: Metadata = {
  title: 'For bedrifter | Start NTNU',
}

export default async function BedriftSide() {
  const params = {slug: 'bedrift'}
  const initial = await loadQuery<SanityDocument>(BEDRIFT_QUERY, params, {
    perspective: draftMode().isEnabled ? 'previewDrafts' : 'published',
  })

  try {
    if (!initial) {
      return notFound()
    }

    return draftMode().isEnabled ? (
      <BedriftPreview initial={initial} params={params} />
    ) : (
      <Bedrift bedriftSide={initial.data} />
    )
  } catch (error) {
    console.error(`Error in BedriftSide: ${(error as Error).message}`)
    return notFound()
  }
}
I'm wondering if this issue has something to do with how I've set up my pages, but I'm not sure. My events page, which uses dynamic parameters, works just fine and doesn't cause any errors when I build it on Vercel. The only difference I see is that for the events page, I'm using dynamic parameters, but for other pages like the landing page, members page, and about us page, I've put in the parameters directly into the code for visual editing purposes. However, those pages give me errors on Vercel, just like the example I mentioned. This issue happens on all four pages where I've done this.
My events (arrangement) page:


// C:\Users\mariu\start\hjemmeside\app\(user)\arrangementer\[slug]\page.tsx
import {loadQuery} from '@/sanity/lib/store'
import ArrangementPreview from '@/components/siderPreview/ArrangementPreview'
import Arrangement from '@/components/sider/ArrangementSide'
import {SanityDocument, QueryParams} from '@sanity/client'
import {draftMode} from 'next/headers'
import {ARRANGEMENT_QUERY} from '@/sanity/lib/queries'
import {notFound} from 'next/navigation'
import type {Metadata, ResolvingMetadata} from 'next'
import {client} from '@/lib/sanity.client'

export default async function ArrangementSide({params}: {params: QueryParams}) {
  const initial = await loadQuery<SanityDocument>(ARRANGEMENT_QUERY, params, {
    perspective: draftMode().isEnabled ? 'previewDrafts' : 'published',
  })
  
  const slug = params.slug
  if (!slug) {
    console.error('Error in ArrangementSide: slug is undefined')
    return <h1>Invalid slug</h1>
  }

  try {
    if (!initial) {
      return notFound()
    }

    return draftMode().isEnabled ? (
      <ArrangementPreview initial={initial} params={params} />
    ) : (
      <Arrangement page={initial.data} />
    )
  } catch (error) {
    console.error(`Error in ArrangementSide: ${(error as Error).message}`)
    return notFound()
  }
}
Hello everyone,I'm still struggeling with this issue. Can anyone spot what's wrong?
Hello helpful people. I've been struggling with this for weeks, and I still can't seem to figure out what's wrong. Could anyone please take another look at it? I'm not able to deploy all my fantastic new updates 😢
Looking at this again, it looks like you’re not passing a token to your preview client.
export const client = createClient({
  projectId,
  dataset,
  apiVersion,
  useCdn: false,
  perspective: 'published',
  stega: {
    enabled: false,
    studioUrl: '/studio',
  },
  token: <your-token-here>
})
Added my token, and got even more errors. Now also for my dynamic pages
//sanity.client.ts
import {createClient} from '@sanity/client/stega'

export const projectId = process.env.NEXT_PUBLIC_SANITY_PROJECT_ID
export const dataset = process.env.NEXT_PUBLIC_SANITY_DATASET
const apiVersion = process.env.NEXT_PUBLIC_SANITY_API_VERSION

export const client = createClient({
  projectId,
  dataset,
  apiVersion,
  useCdn: false,
  perspective: 'published',
  stega: {
    enabled: false,
    studioUrl: '/studio',
  },
  token: process.env.NEXT_PRIVATE_SANITY_API_READ_TOKEN,
})
Nevermind, got it working now! Thank you for your patience 🤠
Glad you got it working!
I was just about to post something here, sorry I didn't see it sooner. Glad you got it working in the end 🥳
Having the same errors! what fixed it
i replaced my private key with a new one. i Suspect there was an extra space at the end of mye key causing the issue

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?