Go Behind the Experience to see how Tecovas brings the West to life with Sanity 🤠 July 18th

I tried to create a serializer for an asset of type file that is part of a PortableText field, in order to display a download link for the file. This is what works for me,...

1 replies
Last updated: Nov 25, 2020
I tried to create a serializer for an asset of type file that is part of a PortableText field, in order to display a download link for the file. This is what works for me, not sure if there are better options, but I couldn’t find a GraphQL way of getting the asset->url (that would have been the GROQ way) into my GatsbyJS site:
import React from 'react'
import css from './downloadableFile.module.scss'

export default ({ node }) => {
  const baseURL = '<https://cdn.sanity.io/files/>'
  const fileName = `${node.file.asset._ref.split('-')[1]}.${node.file.asset._ref.split('-')[2]}`
  const downloadURL = `${baseURL}${process.env.SANITY_PROJECT_ID}/${process.env.SANITY_DATASET}/${fileName}?dl`

  return (
    <div className={css.root}>
      <p>{node.title} <a href={`${downloadURL}`}>Download</a></p>
    </div>
  )
}
Just in case this helps anyone.
Nov 25, 2020, 10:43 AM
If you’re using a raw field you could consider using resolveReferences. See example in this section https://github.com/sanity-io/gatsby-source-sanity/#raw-fields
You don’t get the same level of control over which references are resolved as with GROQ but it’s a useful option.
Nov 25, 2020, 10:48 AM

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?