How to filter a reference field in Sanity schema for localization.
I can help you with filtering references based on the language from @sanity/document-internationalization! The issue in your code is a few syntax errors and you need to use the correct field name that the plugin creates.
When you use @sanity/document-internationalization, it adds a special field called __i18n_lang to your documents to track their language. Here's the corrected filter:
defineField({
name: 'product',
type: 'array',
of: [{type: 'reference', to: [{type: 'dogTreat'}, {type: 'catTreat'}]}],
options: {
filter: ({ document }) => {
const currentLanguage = document.__i18n_lang; // Use __i18n_lang field
return {
filter: '_type == $type && __i18n_lang == $language', // Fixed syntax
params: {
type: 'catTreat',
language: currentLanguage
}
};
}
},
group: 'products',
})Key changes I made:
- Use
__i18n_langfield: The document-internationalization plugin stores the language code in a field called__i18n_lang, notlanguage - Fixed GROQ syntax: Your filter string had template literals mixed with GROQ syntax incorrectly - use parameterized queries instead
- Use
$languageparameter: Pass the language as a param to avoid injection issues
If you want to filter for multiple types, adjust it like this:
filter: ({ document }) => {
const currentLanguage = document.__i18n_lang;
return {
filter: '_type in $types && __i18n_lang == $language',
params: {
types: ['catTreat', 'dogTreat'],
language: currentLanguage
}
};
}This will ensure that when you're editing the en-US version of a document, you'll only see en-US versions of the referenced products in the dropdown. The __i18n_lang field is automatically managed by the plugin alongside __i18n_base and __i18n_refs fields that maintain relationships between translated documents.
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.