How to extract URL from referenced schema in Sanity?

4 replies
Last updated: Jul 20, 2022
Hey everyone, when referencing another schema (
type: "reference"
), how can I extract the URL from that referenced post? At the moment the output only provides me with the _ref and _type, which isn't very useful...


    {
      name: "linkToNews",
      title: "Lien au publication de nouvelles",
      description:
        "Créer un lien vers un article de presse contenant plus d'informations sur les dates limites de soumission.",
      type: "reference",
      to: { type: "nouvelles" },
    },
AI Update

The issue you're experiencing is expected behavior - reference fields in Sanity only store the _ref and _type by default. To get the actual data from the referenced document (including any URL/slug fields), you need to dereference the reference in your GROQ query using the -> operator.

Here's how to resolve your linkToNews reference:

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

The -> operator tells GROQ to fetch the full referenced document. So if your nouvelles document has a slug field, you'll now get access to it.

If you only need specific fields from the referenced document (like just the slug for building a URL), you can be more selective:

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

Or if you need to construct a full URL path:

*[_type == "yourDocumentType"] {
  ...,
  "newsUrl": "/news/" + linkToNews->slug.current
}

The reference access operator documentation has more details, but the key takeaway is: references are just pointers until you explicitly dereference them with -> in your queries.

If you're working with arrays of references, you'd do:

{
  newsLinks[]->
}

This pattern works whether you're querying from the CLI, using the HTTP API, or fetching data in your frontend with @sanity/client or framework integrations like next-sanity.

Show original thread
4 replies
You could expand it using GROQ:
*[_type == 'yourdoc']{ name, linkToNews-> }
see the documentation on joins here: https://www.sanity.io/docs/groq-joins
nice, thanks! That worked and I'm able to query all the data from
linkToNews
, but how would I just extract the
slug
rather than all the data from a given
news
post?
Cool. Here's what you could do:
*[_type == 'nouvelles']{
  name, 'slug': linkToNews->slug
}
awesome, cheers!!

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?