Custom GROQ Request in Sanity Preview/Prepare Functions
Yes, you can access the original filename and other asset metadata in your preview configuration! The key is to use dot notation to dereference the image asset in your select object. Instead of just selecting image, you need to select image.asset and then the specific fields you want from the asset document.
Here's how to modify your code to get the original filename:
export default {
name: 'singleImage',
title: 'Single image',
type: 'object',
fields: [
{name: 'image', type: 'image'}
],
preview: {
select: {
image: 'image',
originalFilename: 'image.asset->originalFilename', // Use -> to dereference
extension: 'image.asset->extension',
url: 'image.asset->url'
},
prepare: ({image, originalFilename, extension, url}) => {
console.log('Original filename:', originalFilename);
console.log('Extension:', extension);
return {
title: originalFilename || 'Single image',
subtitle: extension ? `${extension.toUpperCase()} file` : undefined,
media: image
}
}
}
}The -> operator is the dereference operator in Sanity's select syntax. When you use image.asset->originalFilename, you're telling Sanity to:
- Get the
imagefield - Follow the reference in
image.asset - Retrieve the
originalFilenamefield from the referenced asset document
This works because image assets in Sanity are stored as separate documents in the sanity.imageAsset type, which includes fields like:
originalFilename- The original name of the uploaded fileextension- File extension (jpg, png, etc.)url- The asset URLmetadata- Contains dimensions, palette, etc.
You can also access nested metadata like dimensions:
select: {
image: 'image',
originalFilename: 'image.asset->originalFilename',
width: 'image.asset->metadata.dimensions.width',
height: 'image.asset->metadata.dimensions.height'
}Important limitation: As mentioned in the preview configuration documentation, the prepare function cannot make custom GROQ queries. All data fetching must happen in the select object using this dot notation and dereference syntax. The prepare function only transforms the data that was already selected.
Show original thread5 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.