Next.js Discord

Discord Forum

Will this function work in next js for caching?

Unanswered
Thrianta posted this in #help-forum
Open in Discord
ThriantaOP
This function is suppose to improve upon an image url builder by caching the urls thus reducing data request and improving performance. I am wanting to make sure it is compatible with the way Nextjs functions, also if perhaps there is a more effective way to do this with the caching features of next

import { client } from '@/lib/sanity/client';
import createImageUrlBuilder from '@sanity/image-url';
import type { Image } from 'sanity';

const imageBuilder = createImageUrlBuilder(client);

// Cached images URLs
const imageUrlCache = new Map();

// Helper to build URL
function buildImageUrl(source: Image) {
  // Ensure imageBuilder is defined
  if (!imageBuilder) {
    throw new Error('imageBuilder is not defined');
  }

  return imageBuilder.image(source).auto('format').fit('max');
}

// Main image URL function
export default function urlForImage(source: Image | undefined) {
  // Ensure that source image contains a valid reference
  if (!source?.asset?._ref) {
    return undefined;
  }

  // Use a unique identifier as the cache key
  const cacheKey = source.asset._ref;

  // Check if URL is cached
  if (imageUrlCache.has(cacheKey)) {
    return imageUrlCache.get(cacheKey);
  }

  const url = buildImageUrl(source);
  imageUrlCache.set(cacheKey, url);
  return url;
}

// OpenGraph image URL
export function urlForOpenGraphImage(image: Image | undefined) {
  // Ensure that source image contains a valid reference
  if (imageUrlCache.has(image)) {
    return imageUrlCache.get(image);
  }

  // If no image, return undefined
  if (!image?.asset?._ref) {
    return undefined;
  }

  const url = buildImageUrl(image).width(1200).height(627).fit('crop').url();

  imageUrlCache.set(image, url);
  return url;
}

0 Replies