Auto-generate slug in Sanity HTTP API mutation without manual creation
Great question! Unfortunately, the slug generation "Generate" button you see in Sanity Studio is a Studio-only feature and doesn't work automatically when creating documents via the HTTP API.
When you submit mutations through the HTTP API, you need to manually create the slug object yourself. The auto-generation functionality is part of the Studio interface, not something the API provides as an option.
Create Your Own Slugification Function
You'll need to implement slug generation in your Nuxt app before sending the mutation. Sanity Studio itself uses the speakingurl library internally, so you could use that or any other slugification library:
// Install: npm install speakingurl
import slugify from 'speakingurl'
const myThingyObjectDataGatheredFromTheForm = {
title: "Hello World! How are you?",
price: 222
}
// Generate the slug from the title
const slug = {
_type: 'slug',
current: slugify(myThingyObjectDataGatheredFromTheForm.title)
// This will produce: "hello-world-how-are-you"
}
const mutations = [
{
createOrReplace: {
_type: 'mythingy',
...myThingyObjectDataGatheredFromTheForm,
slug: slug
},
},
]Alternative Libraries
If you don't want to use speakingurl, there are other options:
slugify(npm package)@sindresorhus/slugify- Or write your own simple function:
function createSlug(text) {
return text
.toLowerCase()
.replace(/[^\w\s-]/g, '') // Remove special characters
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/-+/g, '-') // Replace multiple hyphens with single
.trim()
}Why It Works This Way
As explained in this answer about HTTP API slug generation, the slug generation logic lives in the Studio UI layer, not in the Content Lake API itself. This means any external system (like your Nuxt form) needs to handle slugification on its own.
The good news is that once you set up the slugification function, it's pretty straightforward to use! And you have full control over the slug generation logic, which can be helpful for custom requirements like handling special characters or creating custom URL patterns based on your specific needs.
Show original thread3 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.