
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeI can help you fix this GROQ query issue! The problem is with how you're trying to use the references() function. The syntax you have isn't valid GROQ.
The references() function is actually much simpler than what you're attempting. It takes a document ID and checks if any reference field in the document points to it. You don't specify field paths or slugs - it just checks all reference fields automatically.
Here's the corrected query:
const query = groq`*[_type == "article" && references($categoryId)] {
...,
categories[]-> {
title,
slug
}
}`The key changes:
references() function checks against _id values, not slug fields.$categoryId) instead of string interpolation for safety and proper typing.In your code, you'll need to:
_id:const categoryDoc = await client.fetch(
`*[_type == "category" && slug.current == $slug][0]`,
{ slug }
)const articles = await client.fetch(query, { categoryId: categoryDoc._id })Alternative: If you must filter by slug directly, you can use this approach instead:
*[_type == "article" && $slug in categories[]->slug.current] {
...,
categories[]-> {
title,
slug
}
}This dereferences all categories in the array and checks if your slug exists in any of them. However, this can be less performant than using references() with the document ID, because it has to dereference every category reference to check the slugs.
The references() function is specifically designed for checking if a document references another document by ID, which is why it's the recommended and most efficient approach when working with reference fields.
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store