Slug type auto-generation with JS client
You're correct - when using the JavaScript client to create or update documents, the slug field will not be automatically generated. This is by design.
The slug type in Sanity has an auto-generation feature, but this only works in Sanity Studio through the UI. When you define a slug field with a source option in your schema (like source: 'title'), Studio will show a "Generate" button that creates the slug from that source field. However, this generation is a Studio-specific feature - it's handled by the Studio UI, not by the Content Lake or the client libraries.
When you're creating or updating documents via the JavaScript client (like @sanity/client), you need to:
- Generate the slug yourself before sending the document to Sanity
- Include the slug in your mutation as a complete object with a
currentproperty
Here's an example:
import {createClient} from '@sanity/client'
const client = createClient({...})
// You need to generate the slug yourself
const title = "My Blog Post"
const slugValue = title
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w-]+/g, '')
await client.create({
_type: 'post',
title: title,
slug: {
_type: 'slug',
current: slugValue // Must include the 'current' property
}
})The slug type is stored as an object with a current property (and optionally a source property for tracking). When working with the client, you're responsible for generating that value and structuring it correctly.
If you need consistent slug generation across your application, Sanity's own slug function uses speakingurl under the hood. You can use the same library or similar packages like slugify to replicate Studio's behavior. Here's Sanity's internal slugify function as a reference for how they handle it.
Show original thread4 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.