How to add document _id to slug field using custom slugifier function

6 replies
Last updated: Nov 29, 2025
I’m stuck at trying to write a slugifier that adds the current document’s
_id
value to a slug field. My intention is to have a slug that is created based on a couple of values from the same document but I can only have a single source, correct? I’m seeing that a function can also be used as the source, but I’m kinda lost . What would be the best approach? Is there a way to add the
_id
(also slicing the first 7 characters to remove ‘drafts.’)
AI Update

You're on the right track! You can absolutely use a function as the source option in a slug field, and this is the perfect way to combine multiple values including the _id. While the slug field technically takes a single source, that source can be a function that returns a string combining whatever fields you need.

Here's how to set this up to include the _id while removing the drafts. prefix:

{
  name: 'slug',
  type: 'slug',
  options: {
    source: (doc) => {
      // Remove 'drafts.' prefix from _id if it exists
      const cleanId = doc._id?.replace(/^drafts\./, '') || '';
      
      // Combine with other fields as needed
      return `${doc.title}-${cleanId}`;
    },
    maxLength: 96,
    // Optional: customize the slugify function if needed
    slugify: (input) => input
      .toLowerCase()
      .replace(/\s+/g, '-')
      .replace(/[^\w-]+/g, '')
  }
}

The key points here:

  1. Source function: The source option accepts a function that receives the current document (doc) as a parameter, giving you access to all fields including _id
  2. Removing drafts prefix: Use replace(/^drafts\./, '') to strip the drafts. prefix from the beginning of the _id
  3. Combining values: Return a string that combines whatever fields you need - title, date, _id, etc.

If you want to slice just the first 7 characters after removing the prefix, you could do:

source: (doc) => {
  const cleanId = doc._id?.replace(/^drafts\./, '').slice(0, 7) || '';
  return `${doc.title}-${cleanId}`;
}

The slug field documentation covers the basics, and as mentioned in the Sanity community answers about using multiple fields as sources, this function approach is the standard way to combine multiple document values into a single slug.

One thing to keep in mind: the slug generation happens when you click the "Generate" button in Studio, so the _id needs to exist at that point (which it will for existing documents, but new documents won't have an _id until after the first save).

Show original thread
6 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?