Troubleshooting file URL retrieval in Next.js front-end
11 replies
Last updated: Apr 29, 2022
C
Hello everyone, I'm trying to get a file URL to be able to download it from my Next.js Front-end, I have tried "FileURL": file.asset->url, keeps returning undefined, could anyone point me in the right direction?
Apr 29, 2022, 9:16 PM
Hi Crypticz. Can you post the query you’re trying currently and we can adjust it from there?
Apr 29, 2022, 9:20 PM
Thank you. And
fileis currently returning an
assetproperty with a
_typeand
_ref?
Apr 29, 2022, 9:23 PM
Okay, great. In Vision, what do you see when you run this?
*[_type == "portfolio"][0]{ title, file, }
Apr 29, 2022, 9:29 PM
Yes. If you’re getting something like this:
… then your original query should work, unless your slug param isn’t being applied correctly.
"result": { "file": { "_type": "file", "asset": { "_ref": "file-81b6cdbf87a897608ee9816390a523725479cc32-pdf", "_type": "reference" } }, "title": "Some title" }
Apr 29, 2022, 9:39 PM
It’ll all live under
file.file.asset->, so you can either get each property or use a projection like you did for
owninguser.
Apr 29, 2022, 9:47 PM
The former:
The latter:
'fileURL': file.file.asset->url, 'fileSize': file.file.asset->size, // ...
'file': file.file.asset->{ url, size, // ... }
Apr 29, 2022, 9:51 PM
Is this your new query?
const query = `*[_type == "portfolio" && slug.current == $pageSlug][0]{ title, thumbnail, description, slug, "FileInfo": file.file.asset->{ url, size, title }, owninguser->{ name, slug, image }, images }`
Apr 29, 2022, 10:09 PM
And when you say “I changed it to this using
FileInfo.urlthat no longer works,” where are you doing that and are you getting errors, no data, etc.?
Apr 29, 2022, 10:28 PM
Can you access the other properties coming back from your query? If so, have you asked for
FileInfo? Sometimes that looks something like:
export default function Post({ post }) { const { title, FileInfo } = post;
Apr 29, 2022, 11:16 PM
Great. In that case, you could do:
Or you can do this first:
and then use your original link code.
<a href={portfolio?.FileInfo.url}></a>
const { FileInfo } = portfolio;
Apr 29, 2022, 11:20 PM
Sanity– build remarkable experiences at scale
Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.