How to construct proper URLs from Sanity references with different content types?
The key to handling internal links with different document types in Sanity and Next.js is to include information about the document's type in your GROQ query, then use that to construct the appropriate path prefix.
Schema Setup
First, create a reference field for your internal links:
defineField({
name: 'internalLink',
type: 'reference',
to: [
{type: 'page'},
{type: 'blogPage'},
{type: 'authorPage'}
]
})GROQ Query Pattern
When querying your references, fetch both the slug AND the document type:
*[_type == "yourDocType"] {
...,
internalLink-> {
_type,
slug
}
}Helper Function for Path Generation
Create a helper function to map document types to their URL prefixes:
function getPathFromReference(reference: {_type: string, slug: {current: string}}) {
if (!reference?.slug?.current) return '/';
const pathMap: Record<string, string> = {
'page': '', // root level pages
'blogPage': '/blog',
'authorPage': '/author'
};
const prefix = pathMap[reference._type] || '';
return `${prefix}/${reference.slug.current}`;
}Usage in Your Component
import NextLink from 'next/link';
<NextLink href={getPathFromReference(internalLink)}>
{children}
</NextLink>Alternative: Store Path Prefix in Schema
You can also add a pathPrefix field to each document type and query it directly:
defineField({
name: 'pathPrefix',
type: 'string',
initialValue: '/blog',
hidden: true
})Then query:
internalLink-> {
pathPrefix,
"slug": slug.current
}And construct the URL:
const href = `${internalLink.pathPrefix}/${internalLink.slug}`;This pattern ensures your internal links always maintain the correct path structure based on the document type being referenced. The helper function approach is generally cleaner since it centralizes your routing logic in one place, making it easier to maintain when your site structure changes.
For more information on working with reference fields in Sanity, check out the official documentation.
Show original thread8 replies
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.