
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeGreat question! Generating unique slugs via the API is definitely possible, and you have a few options depending on your needs.
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.
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()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.
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:
my-slug-2, my-slug-3)createIfNotExists with a deterministic IDNote: 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.
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