Using a reference field to generate a slug in Sanity Studio.
Yes, you can absolutely dereference a reference field inside the Studio to use it in your slug generation! The key is using the getClient() method available in the slugify function's context parameter.
Here's how you can accomplish this:
import {defineField} from 'sanity'
defineField({
title: "Slug",
name: "slug",
type: "slug",
options: {
source: 'field_that_references_other_page',
slugify: async (input, schemaType, context) => {
const client = context.getClient({apiVersion: '2024-01-01'})
const refId = context.document.field_that_references_other_page._ref
if (!refId) return input
// Fetch the referenced document
const referencedDoc = await client.fetch(
`*[_id == $refId][0]`,
{refId}
)
// Use data from the referenced document
// For example, use its title field
const slugSource = referencedDoc?.title || input
// Slugify the value (you can use a library or custom logic)
return slugSource
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w-]+/g, '')
}
}
})Key points:
- The
slugifyfunction is async - This allows you to fetch data from the Content Lake - Access
getClient()from context - As mentioned in the Sanity reference type documentation, the context parameter provides agetClient()method that you can use to fetch referenced documents - Access the reference ID - Use
context.document.field_that_references_other_page._refto get the ID of the referenced document - Fetch the referenced document - Use the client to query your referenced document with GROQ
- Custom slugification - You'll need to implement your own slugify logic (Sanity Studio uses
speakingurlinternally, but you can use any approach)
If you want to use a more robust slugification library, you can install slugify or speakingurl:
npm install slugifyThen use it in your function:
import slugify from 'slugify'
// ... in your slugify function:
return slugify(slugSource, {lower: true, strict: true})This approach gives you full flexibility to dereference any field from the referenced document and use it to generate your slug. The slug field documentation covers the basics, and there are community examples of using references with slug generation that demonstrate similar patterns.
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.