Sanity client.fetch() returns empty array despite documents existing in dataset
I feel your pain! This is actually a common issue that trips people up, and it's likely related to the perspective setting in your client configuration.
The most common reason you're getting an empty array is that your Sanity client is querying with the published perspective (which is now the default as of API version v2025-02-19), but your documents might only exist as drafts in the dataset. When you create documents in Sanity Studio, they start as drafts (with _id starting with drafts.) and only become "published" documents when you explicitly publish them.
Here's how to debug and fix this:
1. Check if your documents are published
In Sanity Studio, look at your documents and make sure they have a "Publish" button that's been clicked. If they're still drafts, they won't show up in queries using the published perspective.
2. Adjust your client configuration
If you want to see draft documents, you need to configure your client with the previewDrafts perspective or use a token for authentication. Here's how:
import {createClient} from '@sanity/client'
const client = createClient({
projectId: 'your-project-id',
dataset: 'your-dataset',
useCdn: false, // Important: set to false when querying drafts
apiVersion: '2024-01-01', // use a date-based version
perspective: 'previewDrafts', // This will return drafts with fallback to published
token: 'your-read-token' // Required for previewDrafts perspective
})Key things to note:
useCdn: false- The CDN only serves published content, so you need to disable it to see draftsperspective: 'previewDrafts'- This perspective returns draft versions when they exist, falling back to published versionstoken- You need an authenticated token (with read permissions) to access draft content. You can create one in your Sanity project's API settings
3. Alternative: Query for drafts explicitly
If you just want to see what's actually in your dataset, you can query for drafts specifically:
const drafts = await client.fetch("*[_type == 'document' && _id in path('drafts.**')]")
const published = await client.fetch("*[_type == 'document' && !(_id in path('drafts.**'))]")4. Quick debug query
Try this query in your code to see what's actually there:
const allDocs = await client.fetch("*[_type == 'document'] { _id, _type, _updatedAt }")
console.log('Found documents:', allDocs)If this returns empty but Vision shows results, it confirms it's a perspective/CDN issue.
The API versioning changes introduced a shift in the default perspective from raw to published, which is likely what's catching you here. Good luck, and happy Friday! 🎉
Show original thread4 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.