How to set a slug for a product variant in Sanity and how to handle routes in Gatsby for product variants.
Based on the documentation, you can absolutely generate a slug from the title field in your productVariant schema! The slug field type in Sanity has an options.source property that lets you specify which field to use for slug generation.
Here's how to update your productVariant.js schema:
export default {
title: 'Product variant',
name: 'productVariant',
type: 'object',
fields: [
{
title: 'Title',
name: 'title',
type: 'string',
},
{
title: 'Slug',
name: 'slug',
type: 'slug',
options: {
source: 'title',
maxLength: 96
}
},
]
}The key part is adding options: { source: 'title' } to your slug field. This tells Sanity to use the title field as the source when you click the "Generate" button in the Studio.
Important note about nested objects: Since productVariant is defined as type: 'object' (not a document), the source option works a bit differently. When you're inside the variant object in the Studio, source: 'title' will correctly reference the title field within that same variant object.
If you need to reference the parent product's title or combine multiple fields, you can use a function instead:
options: {
source: (doc, options) => options.parent?.title,
// or combine fields:
// source: (doc, options) => `${options.parent?.title} ${doc.title}`
}The options.parent gives you access to the parent document context when working with nested objects, which is particularly useful for your use case.
Once this is set up, when you create or edit a variant in Studio, you'll see a "Generate" button next to the slug field that will automatically create a URL-friendly slug from the variant's title. The slug field automatically converts text to lowercase, replaces spaces with hyphens, and removes special characters to make it URL-safe.
Then in Gatsby, you can append this variant.slug.current to your product slug to create URLs like /products/my-product/blue-variant.
You can read more about slug field configuration in the Sanity 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.