
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeThe 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.
First, create a reference field for your internal links:
defineField({
name: 'internalLink',
type: 'reference',
to: [
{type: 'page'},
{type: 'blogPage'},
{type: 'authorPage'}
]
})When querying your references, fetch both the slug AND the document type:
*[_type == "yourDocType"] {
...,
internalLink-> {
_type,
slug
}
}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}`;
}import NextLink from 'next/link';
<NextLink href={getPathFromReference(internalLink)}>
{children}
</NextLink>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.
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store