Custom Hook To Get Any Cdn File Url From Sanity
  • Work
    ,
  • About
    ,
  • Blog
    ,
  • Contact
Get In Touch
  • Home
  • Work
  • About
  • Blog
  • Contact

Developer & Designer

OreoGrapher © 2024
Published on: Sun May 05 2024
By - OreoGrapher
hooksanityweb dev

Custom hook to get any CDN file URL from sanity

Custom hook to get any CDN file URL from sanity Image

Are you tired of grappling with complexities when it comes to fetching CDN URLs from your Sanity backend? Say goodbye to cumbersome installations and welcome simplicity with open arms! I've developed a custom hook that will effortlessly streamline this process for you.

Introducing

generateFileUrl

A meticulously crafted solution that ensures hassle-free retrieval of CDN URLs from your Sanity assets. Let's dive into the code and explore how this hook works its magic:

const generateFileUrl = (file) => {
  const asset = file?.asset;
  const assetRefParts = asset?._ref.split("-");
  const id = assetRefParts[1];
  const format = assetRefParts[2];
  const projectId = process.env.NEXT_PUBLIC_SANITY_PROJECT_ID;
  const dataset = process.env.NEXT_PUBLIC_SANITY_DATASET;
  const hostname = process.env.NEXT_PUBLIC_SANITY_HOSTNAME;

  const url = `https://${hostname}/files/${projectId}/${dataset}/${id}.${format}`;

  return url;
};

export default generateFileUrl;

This elegant function takes a file object as input and swiftly generates the corresponding CDN URL. Here's a breakdown of how it operates:

  • Extracting Asset Information: The function extracts essential information from the provided file object, such as the asset reference, ID, and format.
  • Constructing the URL: Using the extracted details along with your Sanity project ID and dataset, the function dynamically constructs the CDN URL.
  • Return the URL: Finally, the function returns the generated URL, ready for immediate use in your application.

There's no need to clutter your project with unnecessary packages or struggle with convoluted configurations. Seamlessly integrate this custom hook into your workflow and enjoy a seamless experience when retrieving CDN URLs from your Sanity assets.

Leave a Comment

No comments yet

Similar Blogs

(0)