Generate unique slug via Sanity API - built-in functionality or custom?

3 replies
Last updated: Jul 17, 2023
Hi everyone - another question that I hope you can help with 🙂Is it possible to generate a unique slug (making sure it’s unique) via the API using some out-of-the-box functionality, a library or plugin?
Or would I need to build/find an external slugifier, make an API request to check that it’s unique, and then a request to insert/update the document?
AI Update

Great question! Generating unique slugs via the API is definitely possible, and you have a few options depending on your needs.

Using Sanity's Built-in Slug Uniqueness

The good news is that Sanity's slug type has built-in uniqueness checking through the isUnique option. By default, this checks uniqueness across all documents of the same type. However, this validation primarily works in the Studio UI when users click the "Generate" button.

For API-Based Slug Generation

When creating documents via the API, you'll need to handle slug generation and uniqueness checking yourself. Here's the typical approach:

1. Generate the slug using a slugifier library (like slugify on npm)

2. Check uniqueness with a GROQ query before inserting:

const client = sanityClient({...})

// Check if slug exists
const query = `!defined(*[_type == $docType && slug.current == $slug][0]._id)`
const isUnique = await client.fetch(query, { 
  docType: 'yourDocType', 
  slug: proposedSlug 
})

if (!isUnique) {
  // Handle collision - append number, regenerate, etc.
}

3. Use transactions to minimize race conditions:

await client.transaction()
  .create({
    _type: 'yourDocType',
    slug: { _type: 'slug', current: uniqueSlug },
    // other fields...
  })
  .commit()

Alternative: Sanity Functions

For a more integrated approach, consider using Sanity Functions to create a serverless endpoint that handles slug generation with proper uniqueness checking. This keeps the logic close to your content and automatically scales.

Handling Collisions

The Sanity docs show a custom isUnique function example that checks across all documents in your dataset. You can adapt this pattern for API usage by:

  • Appending a counter (my-slug-2, my-slug-3)
  • Using createIfNotExists with a deterministic ID
  • Implementing retry logic

Note: There's no built-in "slug reservation" system, so in high-concurrency scenarios, you may need to handle the rare case where two requests generate the same slug simultaneously. Using Sanity's transaction API helps minimize this risk.

Show original thread
3 replies
You’d need to go with the latter option 🙂
Thank you! 🙂
You’re welcome!

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?