Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Ignoring drafts in Groq requests without having to specify the filter each time.

11 replies
Last updated: Feb 18, 2021
Is there a way to ignore all drafts and not have to
!(_id in path('drafts.**'))
in every groq requests?
Feb 17, 2021, 7:57 PM
HI User. Are you sending a token with your request? If you’re querying a public dataset then drafts will be ignored if no token is sent. I’m not sure if that’s possible in your setup.
Feb 17, 2021, 8:00 PM
Hmm i’d prefer the dataset remains private to be honest
Feb 17, 2021, 8:00 PM
Fair enough. If it’s a private dataset then I’m not sure if you can get around some sort of filter to remove the drafts.
Feb 17, 2021, 8:01 PM
user A
I assume you’re using a read+write token for your query. What about using a read token for those cases where you want to ignore drafts? It looks like that should work, though of course your circumstances will dictate.
Feb 17, 2021, 8:12 PM
I use a defined constant for this, so it doesn’t need to be re-written each time:In a constants.js file

_export_ const QUERY_OMIT_DRAFTS = "!(_id in path('drafts.**'))"

groq`*[
      _type == 'glossary'
      && ${QUERY_OMIT_DRAFTS}
    ]|{
      _id,
      title,
      name,
      "slug": slug.current,
      categories[]->{_id, title, name, "slug": slug.current}
    }`
Feb 17, 2021, 8:58 PM
It’s not ideal, but it’s easier than remembering the syntax to omit the drafts
Feb 17, 2021, 8:58 PM
I was curious if using template literal placeholders (
${QUERY_OMIT_DRAFTS}
) like that is safe, since other parameters are passed into the query. Any thoughts on that
user A
?
Feb 17, 2021, 9:01 PM
I can’t imagine it being a problem, though my experiences are limited. Maybe a fallback in case it fails would help? Although it’s possible it fails gracefully on its own.
Feb 17, 2021, 9:03 PM
My mind is on the idea of SQL injection (which is different than this) but wasn’t sure if there was any similar security risk in this approach, as GROQ offers the ability to pass parameters in, which maybe is more safe… I haven’t been able to find any information on it, but this is definitely the more convenient approach.
Feb 17, 2021, 9:16 PM
Oh, gotcha. Thank you. 👍 I think that would be okay as you can’t mutate from a GROQ query, but it’s something to think on, for sure.
Feb 17, 2021, 9:42 PM
Yeah
user J
I ended up doing something similar. Thanks everyone 🙏
Feb 18, 2021, 1:42 PM

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?