Slug type auto-generation with JS client

4 replies
Last updated: Jun 16, 2023
Hi, I have a question about the slug type when we use js client. The client will not generate right?
AI Update

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:

  1. Generate the slug yourself before sending the document to Sanity
  2. Include the slug in your mutation as a complete object with a current property

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 thread
4 replies
Correct. Slug generation is not automatic. When you mention using the JS client, do you mean to create/patch documents or to fetch them?
create on, on the create/patch, the slug will not be generated right?
Right. You could implement this yourself, if you wanted to and have the necessary data (e.g., the title), but it won’t happen automatically.
I presumed this. I just wanna have shure because this information is not clear at documentation.

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?