How to construct proper URLs from Sanity references with different content types?

8 replies
Last updated: Nov 29, 2025
I am using Sanity with Nextjs.Let say that i have pages, blogPage and authorPage.
Then i want to create internalLink. I am creating references to those 3 types.
how should i use slug i am getting in correct way?
I do not want to omit /blog/ or /author/ . Page type can also be /whatever

<NextLink href={slug}>{children}</ NextLink> 
AI Update

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 thread
8 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.

Was this answer helpful?