Discussion on creating custom slugs for documents in Sanity and simplifying the process of turning references into links.
You can store whatever you want in a Sanity slug field – it's just a string field with some helpful generation features built in. By default, Sanity only stores the document's own slug (like sydney), not the full path. But there's nothing stopping you from storing full paths like /office/sydney in the slug field.
Your approach of storing the complete path in the slug is totally valid and can definitely simplify your routing logic! Here's what you should know:
Storing Full Paths
The slug field type stores whatever string you put in slug.current. You can absolutely store /office/sydney instead of just sydney. This works fine in Sanity and can make your frontend routing much cleaner since you won't need to reconstruct paths from references.
Custom Slugify Function
You can use the slugify option to implement your custom path logic. Here's a basic example:
{
name: 'slug',
type: 'slug',
options: {
source: (doc) => {
// Your logic to construct the full path
if (doc.parent?._ref) {
// Fetch parent slug and prepend it
return `/office/${doc.title}`
}
return doc.title
},
slugify: (input) => {
// Custom slugification that preserves your path structure
return input
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w\-\/]/g, '') // Keep slashes!
}
}
}Important Considerations
isUnique validation: If you're using the isUnique validator, be aware that it checks uniqueness across all documents of that type. With full paths, this should work fine since each path should be unique anyway.
References and hierarchy: If you're building paths based on parent-child relationships (like /office/sydney where "sydney" is a child of "office"), you might need to handle updates when parent slugs change. The slugify function only has access to the current document, so for reference-based paths, you may need to use a custom input component or document action to fetch and construct the full path.
The Trade-off
The downside of storing full paths is that if you ever restructure your content hierarchy or rename a parent, you'll need to update all child document slugs. With just storing the document's own slug, you'd reconstruct paths at query time, which automatically reflects hierarchy changes.
But if the simplicity of having ready-to-use paths in your frontend outweighs this maintenance concern (which it often does!), then go for it. Many developers find this approach cleaner than constantly piecing together paths across their codebase.
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.