How to use patch().set() to update a slug field in Sanity?

4 replies
Last updated: May 30, 2022
Is there a way to use the
patch
set
function to set a slug? I've made a few attempts, but each time I get complaints about it being a
string
or
number
.
AI Update

Yes, you can definitely use the patch().set() function to set a slug! The key thing to understand is that slug fields in Sanity have a specific structure - they're stored as an object with a _type and current property, not just as a plain string.

Here's the correct way to set a slug using the Sanity client's patch().set():

client
  .patch('document-id')
  .set({
    slug: {
      _type: 'slug',
      current: 'my-slug-value'
    }
  })
  .commit()

The errors you're getting about it being a "string or number" are likely because you're trying to set the slug as a simple string like this (which won't work):

// ❌ This won't work
.set({ slug: 'my-slug' })

Instead, you need to provide the full slug object structure with both _type: 'slug' and the current property containing your actual slug string.

If you want to update just the slug value on an existing slug field, you can also use dot notation:

client
  .patch('document-id')
  .set({
    'slug.current': 'my-new-slug-value'
  })
  .commit()

This approach is useful when you know the slug field already exists and you just want to change the current value without having to specify the entire object structure.

According to the Sanity slug documentation, the slug value is always stored on the current property of a slug object, which is why you need this specific structure when patching.

Show original thread
4 replies
You can. A
slug
is an object with a
_type
(always
'slug'
) and a
current
value (that’s what you want the slug to be), so you’ll need to make sure to patch the entire object.
So would that be something like this?

patch.execute([
  {
    set: {
      slug: { _type: "slug", current: query },
    },
  },
]);
Or is there a better way?
😅
I’m not familiar with patch.execute, but I tested the following and it worked:

client
  .patch(docId)
  .set({slug: {_type: "slug", current: query}})
  .commit()
  .then((updatedDoc) => {
    console.log('Update successful! New document:')
    console.log(updatedDoc)
  })
  .catch((err) => {
    console.error('Update failed: ', err.message)
  })
I'll give that option a look, thank you 🙂

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?