How to convert Sanity file asset reference to downloadable URL?

3 replies
Last updated: Jun 10, 2023
hi! how can i convert this json to a readable url on the client that links to the asset.
"audio": {
    "_type": "file",
    "asset": {
      "_ref": "file-595808d57da3d3513d1410f284c538c435bca8a3-wav",
      "_type": "reference"
    }
  },
I've used
imageUrlBuilder
for images but not sure how to achieve this with audio (file type). is there another plug-in?Thanks
AI Update

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-utils

Usage

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.url

Key Differences from Images

  • Images: Use imageUrlBuilder from @sanity/image-url for transformation capabilities (resize, crop, format conversion)
  • Files: Use @sanity/asset-utils to 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 thread
3 replies
Hi
user C
. You can dereference the asset in your GROQ query to return all of the properties.

audio{
  ...,
  asset->
}
thanks will read more on this
Works! πŸ™

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.

Was this answer helpful?