Unlock seamless workflows and faster delivery with our latest releases – get the details

Resolving references in the structure builder for constructing a URL in Sanity.io.

11 replies
Last updated: Mar 4, 2022
Hi!
I'm setting up a preview iframe pane, and creating a
resolveProductionUrl
function, like in many of the guides suggests. I have done it before, and it works great. Usually.
However, now I want to construct the URL from a referenced field. I have an
article
schema type, that has a reference to a
category
type. The URL is basically
${article.category.slug.current}/${article.slug.current}
. However, the doc passed by the
S.view.options({ url: resolveProductionUrl })
function (where S is the structure builder) doesn't resolve references (so
article.category
is just a regular ref object.
How can I resolve that doc?
Mar 2, 2022, 5:50 PM
Anyone know how to resolve references in the structure builder?
Mar 4, 2022, 7:10 AM
What does your
resolveProductionUrl
function look like?
Mar 4, 2022, 6:57 PM
It's pretty basic

export const resolveProductionUrl = (doc: any) => {
  const host = window.location.href.includes("localhost")
    ? "<http://localhost:3000>"
    : "<https://production.domain>";

  return `${host}/${doc.category.slug?.current}/${doc.slug.current}?preview=${process.env.SANITY_PREVIEW_SECRET}`;
};
However,
doc.category
is just an object containing a
_ref
to the category ID
Mar 4, 2022, 7:02 PM
Ah got it! So, set up that way, your function has no way to resolve the category reference. You'll have to import the client:
import client from "part:@sanity/base/client"

const sanityClient = client.withConfig({apiVersion: '2021-03-25'})
Then fetch the category values before returning the url.
Mar 4, 2022, 11:03 PM
Ah got it! So, set up that way, your function has no way to resolve the category reference. You'll have to import the client:
import client from "part:@sanity/base/client"

const sanityClient = client.withConfig({apiVersion: '2021-03-25'})
Then fetch the category values before returning the url.
Mar 4, 2022, 11:03 PM
Oh that’s how that’s done within the studio. Are there docs about the studio client I missed somehow?
Mar 4, 2022, 11:06 PM
Thanks!
Mar 4, 2022, 11:06 PM
I know it exists in the docs, but I can't remember where. I'll look around for it.
Mar 4, 2022, 11:07 PM
I know it exists in the docs, but I can't remember where. I'll look around for it.
Mar 4, 2022, 11:07 PM
Well, don’t spent your time doing that. I’ll find it myself. Thanks for showing me though 😍
Mar 4, 2022, 11:08 PM
Well, don’t spent your time doing that. I’ll find it myself. Thanks for showing me though 😍
Mar 4, 2022, 11:08 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?