Is there a way to change the slug so that it reflects its content type?

2 replies
Last updated: Oct 28, 2020
Hi all! Is there a way to change the slug so that it reflects its content type? Like a project has slug
/projects/the-title-of-the-project/
and a blog post has slug
/blog/title-of-the-article/
.
AI Update

The slug field in Sanity stores just the URL-friendly identifier (like the-title-of-the-project), but you absolutely can customize how slugs are generated to include content type prefixes! Here are a few approaches:

Option 1: Customize the Source Function

You can modify the source option in your slug field to include a prefix based on the document type:

{
  name: 'slug',
  type: 'slug',
  options: {
    source: (doc) => `projects/${doc.title}`,
    maxLength: 96
  }
}

This will generate slugs like projects/the-title-of-the-project directly in the slug field.

Option 2: Custom Slugify Function

For more control, use the slugify option to add custom logic:

{
  name: 'slug',
  type: 'slug',
  options: {
    source: 'title',
    slugify: (input, schemaType, context) => {
      const prefix = context.parentPath[0]._type === 'project' ? 'projects' : 'blog'
      return `${prefix}/${input.toLowerCase().replace(/\s+/g, '-')}`
    }
  }
}

Option 3: Handle Prefixes in Your Frontend

Many developers prefer keeping slugs simple in Sanity and adding the content type prefix when building routes in their frontend application. For example, in Next.js:

// In your routing logic
const url = doc._type === 'project' 
  ? `/projects/${doc.slug.current}`
  : `/blog/${doc.slug.current}`

This approach keeps your slugs cleaner and more portable, and it's easier to restructure your URL patterns later without migrating content.

The third option is generally recommended because it separates content concerns from routing logic, but all three approaches work depending on your needs. The slug field documentation covers the technical details of source and slugify options if you want to dive deeper.

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