#Vercel caching not working

1 messages · Page 1 of 1 (latest)

rancid hullBOT
#

Hi @languid dust. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the knowledge sources provided and your question, I can offer some guidance on how to modify your fetchRecords function to use caching in Next.js. However, it's important to note that the specific fetchWithCache function you've provided is not a standard Next.js or Vercel function, and some of its implementation details (like hashBody) are not defined in the knowledge sources.

Instead, I can show you how to use Next.js built-in caching mechanisms. Here's how you can modify your fetchRecords function to use Next.js caching:

export const fetchRecords = async (query, id) => {
  const url = `${API_ROOT}/v1/objects/record/${id}`;

  try {
    const response = await fetch(url, {
      method: "POST",
      body: JSON.stringify(query),
      headers: {
        "Content-Type": "application/json",
      },
      next: {
        revalidate: 3600, // Cache for 1 hour
        tags: ['records'], // Optional: Add a tag for cache invalidation
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error("Error fetching record:", error);
    throw error;
  }
}

This implementation uses Next.js built-in fetch with caching options. Here's what changed:

  1. We removed the fetchWithCache wrapper and used fetch directly.
  2. We added the next option to the fetch call, which is specific to Next.js 13 and later versions.
  3. The revalidate option sets the cache duration to 1 hour (3600 seconds). You can adjust this value as needed.
  4. We added a tags option, which allows for on-demand revalidation of this specific fetch call.
#

This approach leverages Next.js Data Cache, which is automatically enabled when you deploy a Next.js project that uses App Router to Vercel Vercel Data Cache.

If you need to invalidate the cache for this specific fetch, you can use the revalidateTag function:

import { revalidateTag } from 'next/cache';

// In a server action or API route:
revalidateTag('records');

This will invalidate all fetches tagged with 'records', causing them to refetch data on the next request.

Remember that for this caching to work, you need to be using Next.js 13 or later with the App Router. If you're using an older version or the Pages Router, the caching behavior will be different.

Next.js Caching provides more details on how caching works in Next.js.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: