How to access file asset URL in Sanity query for PDF download link?

10 replies
Last updated: Jun 23, 2022
Hi there, I'm trying to query for a pdf that I've saved on sanity. It is of the type: "file". It currently looks like this when I print it:
PDF: { _type: 'file', asset: [Object] },

I want to access the object for its url so I can use it in an href like so:

<a href={pdf}/>

I tried like the docs suggest but it doesn't seem to work:

PDF{

asset->url

},
AI Update

The issue is that you need to dereference the asset properly in your GROQ query. The syntax you're using is close, but it needs a slight adjustment.

Your current query:

PDF{
  asset->url
}

This should actually be:

"pdf": PDF.asset->url

Or if you want to keep the entire PDF object structure and add the URL:

PDF{
  ...,
  "url": asset->url
}

The key is using dot notation (PDF.asset->) rather than just querying inside the object. The -> operator dereferences the asset reference to get the actual asset document, and then you access its url property.

So your full query might look something like:

*[_type == "yourDocumentType"]{
  "pdfUrl": PDF.asset->url
}

Then in your component, you can use it directly:

<a href={pdfUrl}>Download PDF</a>

Bonus tip: If you want the file to trigger a download instead of opening in the browser, append ?dl to the URL:

<a href={`${pdfUrl}?dl`}>Download PDF</a>

This works because Sanity's asset URLs support the ?dl query parameter to force downloads, which is especially useful since the standard HTML download attribute doesn't work across different origins.

Show original thread
10 replies
What doesn’t work? What data do you receive from your query? 🙂
It is a PDF file.
What doesn't seem to work is trying to unpack the object for its URL?
Hence why I ask what you get back from your query. Can you log it? 🙂
Yes, it looks like this:
PDF: { _type: 'file', asset: [Object] },
or otherwise this:
{

_type: 'file',

asset: {

_ref: 'file-f3654343bdaadea9dd8f256455b63afdc270637a-pdf',

_type: 'reference'

}

}
Right, to that means the asset hasn’t been resolved. Can you show the way you declare the field in your schema and your query itself?
Sure it looks like this:

{

name: "PDF",

title: "PDF",

type: "file",

description: "The pdf",

},
Alright, can you try this please?
"PDF": PDF.asset -> url
ahh voila! That worked. Thanks 🙂
Yay, amazing. 🙂

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?