How to specify the dataset to query in GROQ for an app using Sanity.io.
When you're working with multiple datasets in Sanity (like one public and one private), you need to specify which dataset to query by configuring it in your Sanity client. By default, the client uses whatever dataset you specified when you created it, so to query your private dataset, you'll need to either:
1. Create a separate client instance for your private dataset:
import { createClient } from '@sanity/client'
// Client for public dataset
const publicClient = createClient({
projectId: 'your-project-id',
dataset: 'public', // your public dataset name
apiVersion: '2024-01-01',
useCdn: true,
})
// Client for private dataset
const privateClient = createClient({
projectId: 'your-project-id',
dataset: 'private', // your private dataset name
apiVersion: '2024-01-01',
useCdn: false, // don't use CDN for private data
token: 'your-auth-token', // required for private datasets
})
// Now query the private dataset
const data = await privateClient.fetch('*[_type == "article"]')2. Or use the same client with the .withConfig() method:
const client = createClient({
projectId: 'your-project-id',
dataset: 'public',
apiVersion: '2024-01-01',
})
// Query private dataset by overriding the dataset config
const privateData = await client
.withConfig({
dataset: 'private',
token: 'your-auth-token'
})
.fetch('*[_type == "article"]')Important considerations:
- Authentication is required for private datasets. You'll need to include a valid authentication token with appropriate read permissions for the private dataset.
- Don't use CDN (
useCdn: false) when querying private datasets, as the CDN caches responses and could expose private data. - Never expose tokens in frontend code. If you're querying private datasets from a browser, you should proxy those requests through your own backend/API routes to keep tokens secure, as mentioned in Sanity's security documentation.
The dataset is specified at the client configuration level, not within the GROQ query itself. The GROQ query syntax remains the same regardless of which dataset you're querying—you just need to point your client at the correct dataset.
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.