Error fetching data from Sanity using Next.js and getServerSideProps

9 replies
Last updated: May 11, 2022
HI! Yesterday I followed ta YT tutorial on sanity and something else. This is my first time using sanity, so I spent roughly 24 hours trying to fix the error I got. Essentially I, am exporting an object using SanityClient just like in docs using the correct projectId and token.
import sanityClient from '@sanity/client';
import imageUrlBuilder from '@sanity/image-url';

export const client = sanityClient({
  projectId: '********', // commented out intentionaly
  dataset: 'production',
  apiVersion: '2022-05-08',
  useCdn: true,
  token: process.env.NEXT_PUBLIC_SANITY_TOKEN
});

const builder = imageUrlBuilder(client);

export const urlFor = (source) => builder.image(source);
Then I created two schemas for which I also created entries in my
sanity.io/desk and imported them to schema.js file
import createSchema from 'part:@sanity/base/schema-creator';

import schemaTypes from 'all:part:@sanity/base/schema-type';

import product from './product';
import banner from './banner';

export default createSchema({
  name: 'default',
  types: schemaTypes.concat([ product, banner ]),
})
I am using Next.js so I used
getServerSideProps
to fetch the data this way:
export const getServerSideProps = async () => {
  const query = '*[type == "product"]';
  const products = await client.fetch(query);

  const bannerQuery = '*[type == "banner"]';
  const bannerData = await client.fetch(bannerQuery);

  return {
    props: { products, bannerData },
  };
};
However, when I console.log(products) I get returned an empty array without any errors. Do you know what went wrong or at least a way to debug this? I cannot seem to get any data back from sanity.
AI Update

Based on your code, I can see a few potential issues. The most likely culprit is that you're querying for published documents, but your content might only exist as drafts in Sanity Studio.

The Draft vs Published Issue

When you create documents in Sanity Studio, they initially exist as draft documents with IDs prefixed by drafts.. Your query *[_type == "product"] by default only returns published documents (without the drafts. prefix). If you haven't explicitly published your documents, they won't show up in your query results.

To fix this, you have a few options:

Option 1: Publish your documents in Studio

Go to your Sanity Studio, open each product and banner document, and click the "Publish" button. This will create published versions that your query can find.

Option 2: Use the previewDrafts perspective

Modify your client configuration to include drafts:

export const client = sanityClient({
  projectId: '********',
  dataset: 'production',
  apiVersion: '2022-05-08',
  useCdn: true,
  token: process.env.NEXT_PUBLIC_SANITY_TOKEN,
  perspective: 'previewDrafts', // This will show drafts with published fallback
});

The previewDrafts perspective prioritizes draft documents over published versions, which is perfect for development.

Option 3: Query for drafts explicitly in GROQ

You can modify your query to exclude draft IDs:

const query = '*[_type == "product" && !(_id in path("drafts.**"))]';

Or score drafts higher to prioritize them:

const query = '*[_type == "product"] | score(_id in path("drafts.**")) | order(_score desc)';

Other Potential Issues

Token visibility issue

Your token is stored in process.env.NEXT_PUBLIC_SANITY_TOKEN. The NEXT_PUBLIC_ prefix makes it available on the client-side, which is fine for read operations. However, make sure:

  1. The token exists in your .env.local file
  2. You've restarted your Next.js dev server after adding the env variable
  3. The token has read permissions for your dataset

API Version and CDN

Since you're using useCdn: true with a token, be aware that CDN caching and tokens can sometimes conflict. For development, try setting useCdn: false to rule out caching issues.

Legacy imports

Your schema.js is using the old Studio v2 syntax (part:@sanity/base/schema-creator). If you're following an old tutorial, this might work, but be aware that newer tutorials use Studio v3 syntax.

Quick Debug Steps

  1. Check if documents exist: Go to https://yourstudio.sanity.studio/desk and verify your products and banners are there
  2. Check document IDs: Click on a document and look at the URL - if it contains drafts., they're unpublished
  3. Test in Vision: In your Studio, go to the Vision plugin (usually in the toolbar) and run your query there to see what returns
  4. Console log the client config: Add console.log(client.config()) to verify your configuration is correct

The most common fix is adding perspective: 'previewDrafts' to your client config or publishing your documents in Studio. Let me know if that resolves it!

Hey there! You'll want to change your queries from
type
to
_type
.
I can't believe, it worked! Can't believe it was that small of an error. Thank you so much!πŸ™‚
You're welcome! Glad it was such a quick fix! πŸ‘Š
user E

You probably do not want your token to be publicly available with
process.env.NEXT_PUBLIC_SANITY_TOKEN
Isn't it enough that I added it to the .env file and added that to gitignore?
Variables prefixed with
NEXT_PUBLIC
will be exposed to the client and added to the build.
You should read up on
https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser
Haven't personally tested this, but I believe you can just
console.log(NEXT_PUBLIC_SANITY_TOKEN)
in the browser console and anyone can easily retrieve your token and get access to your Sanity account
Just tested this myself, and can confirm that you can see the API key in clear text in Network->Response (if you use Firefox)
Thank you so much for this, I'll read up!

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?