How to convert Sanity file asset reference to downloadable URL?
You're working with Sanity file assets (audio in this case), and you want to convert the asset reference to a readable URL on the client. While imageUrlBuilder works for images, file assets need a different approach.
For file assets, you'll want to use the @sanity/asset-utils package. This utility library provides functions specifically designed to build URLs from file asset references.
Installation
npm install @sanity/asset-utilsUsage
import { buildFileUrl } from '@sanity/asset-utils'
// Your audio field data
const audio = {
_type: "file",
asset: {
_ref: "file-595808d57da3d3513d1410f284c538c435bca8a3-wav",
_type: "reference"
}
}
// Build the URL
const audioUrl = buildFileUrl(audio.asset._ref, {
projectId: 'your-project-id',
dataset: 'your-dataset'
})
// Use it in your component
<audio controls src={audioUrl}>
Your browser does not support the audio element.
</audio>Alternative: Using getFileAsset
If you want more information about the file (like the full asset document structure), you can use getFileAsset:
import { getFileAsset } from '@sanity/asset-utils'
const fileAsset = getFileAsset(audio.asset._ref, {
projectId: 'your-project-id',
dataset: 'your-dataset'
})
// fileAsset.url will contain the full URL
const audioUrl = fileAsset.urlKey Differences from Images
- Images: Use
imageUrlBuilderfrom@sanity/image-urlfor transformation capabilities (resize, crop, format conversion) - Files: Use
@sanity/asset-utilsto build direct URLs - files are served as-is without transformations
The @sanity/asset-utils package handles all asset types (images and files) and can parse various input formats (asset references, IDs, URLs, paths) to give you a working URL. This is the standard way to work with file assets in Sanity on the client side!
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.