How to Get a Slug From a Reference

11 replies
Last updated: Nov 7, 2021
Hey everyone, I think this is an easy one; how do you get a slug from a reference? I have a reference to another page I want to act as a link to another page, but I only get the
_ref
returned and not the
slug
AI Update

Perfect! This is a common situation when working with references in Sanity. By default, references only return the _ref field (which is just the document ID), but you can easily get the full referenced document including the slug using the reference access operator (->).

Basic Solution

If you have a reference field like linkedPage, you can dereference it in your GROQ query using ->:

*[_type == "yourDocumentType"] {
  ...,
  linkedPage->
}

This will replace the reference with the entire referenced document, including the slug.

Getting Just the Slug

If you only need the slug (not the entire referenced document), you can project just that field:

*[_type == "yourDocumentType"] {
  ...,
  linkedPage->{
    slug
  }
}

Or even more concisely, access the slug directly:

*[_type == "yourDocumentType"] {
  ...,
  "pageSlug": linkedPage->slug.current
}

For Arrays of References

If you have an array of page references, you can dereference all of them:

*[_type == "yourDocumentType"] {
  ...,
  relatedPages[]->{
    slug
  }
}

The reference access operator works by internally executing a subquery to fetch the referenced document and merge it into your results. Just keep in mind that each -> does perform an additional query, so be mindful of performance when dereferencing large arrays or deeply nested references.

in your groq query you can do something like this:

{"slug" : reference->slug.current}
Thanks
user H
— what if you're just returning the entire query though? I have a load of blocks for building content and don't want to have to type all of them out
Hey
user S
you can just use a spread operator there so

{…, "slug" : reference->slug.current}
Thanks
user H
, I actually just stumbled upon this as you posted it but thanks so much for the fast reply
groq really is awesome
It's great isn't it!
Sorry
user H
one last question, I have another set of data I need to grab a reference from but it's nested and a bit fuzzy...
How would I resolve these types of references? Something like

[].blocks[].link->slug.current

I'm new to groq so just trying to understand
Ah, got it...
  *[_type == "page" && slug.current == 'values-and-beliefs'] {
    blocks[] {"link": link->slug.current, ...},
    ...
  }
Ah, got it...
  *[_type == "page" && slug.current == 'values-and-beliefs'] {
    blocks[] {"link": link->slug.current, ...},
    ...
  }
Thanks again for your help

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.

Was this answer helpful?