Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Troubleshooting file URL retrieval in Next.js front-end

11 replies
Last updated: Apr 29, 2022
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
file
is currently returning an
asset
property with a
_type
and
_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:

"result": {
  "file": {
    "_type": "file",
    "asset": {
      "_ref": "file-81b6cdbf87a897608ee9816390a523725479cc32-pdf",
      "_type": "reference"
    }
  },
  "title": "Some title"
}
… then your original query should work, unless your slug param isn’t being applied correctly.
Apr 29, 2022, 9:39 PM
Okay, thanks for that. Looks like you want
"FileURL": file.file.asset->url
.
Apr 29, 2022, 9:43 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:

'fileURL': file.file.asset->url,
'fileSize': file.file.asset->size,
// ...
The latter:


'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.url
that 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:

<a href={portfolio?.FileInfo.url}></a>
Or you can do this first:


const { FileInfo } = portfolio;
and then use your original link code.
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.

Was this answer helpful?