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.
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:
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.