✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

Obtaining dataset in Sanity v3 and accessing client in non-component file

9 replies
Last updated: Feb 20, 2023
Hello team! I need some help with a query that is returning posts if they are published but comes back with null if they are only drafts. What is weirder is that on the Vision pane it works but on my Nextjs client it doesn't. I am using a token with max permissions, that I generated in my project -> API -> Tokens, in my
like this:
import { createClient } from "next-sanity";

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

export const client = createClient({
    useCdn: false,
This is the query on my Nextjs, it works for published posts:

*[_type=='post' && slug.current == $slug][0]
On the Vision pane if I do
*[_type=='post' && slug.current == $slug][0]
for the query and
{  "slug": "second-post" }
for the params (
is the slug for an unpublished post) it shows up. On my Nextjs it comes back null.
Has anybody encountered this?
Feb 20, 2023, 12:33 AM
I’m not 100% sure but you could update your query to something like this:

[_type=='post' && slug.current == $slug]
You have to drop the
as it only returns 1 result. When there is a draft, it returns two results of the query you’re working on.
Feb 20, 2023, 5:34 AM
Hi Dorell, thank you for your help. I don't think that is it, the [0] means that i only want the first item that corresponds to my $slug as i am using this query for an individual post page. I think the problem lies somewhere with the authentication of the query because if i do it in Vision it works
Feb 20, 2023, 9:18 AM
perhaps you might need to specify the client version
Feb 20, 2023, 10:22 AM
I actually got it to work!!
Feb 20, 2023, 10:23 AM
it was the token actually, i had generated a token with the wrong permissions.. im an idiot 🤦‍♂️
Feb 20, 2023, 10:24 AM
oh. glad to hear
Feb 20, 2023, 10:24 AM
you’ve made it work. not that you’re an idiot.
Feb 20, 2023, 10:24 AM
appreciate your help!! sorry for wasting your time
Feb 20, 2023, 10:24 AM
no problem
Feb 20, 2023, 10:24 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?