How to disable caching and fetch latest data from Sanity?

11 replies
Last updated: Apr 10, 2023
Hi, I'm trying to get the latest information from my sanity database and I can see that it's updated in my desk, but my fetch just keeps getting old information. Is there anyway to only fetch the latest information?
const getUserCart = async (req, res) => {
  try {
    const currentUserId = req.userInfo.userId;
    const carts = await client.fetch(
      *[_type == "carts" && userId == $userId],
      {
        userId: currentUserId,
        force: true,
      }
    );
    res.json(carts);
  } catch (error) {
    console.log({ message: "Failed to get user cart" });
  }
};
AI Update

I can see the issue! You're fetching data but getting stale content even though it's updated in the Studio. This is a common caching issue with Sanity's CDN, and there are a few solutions.

The main problem is that Sanity's Content Lake uses a CDN that caches responses for performance. Your force: true parameter isn't actually a valid Sanity client option, so it's not doing anything to bypass the cache.

Here are the proper solutions:

The perspectives feature lets you control which version of content you're querying. By default, you might be hitting cached published content. Try adding the perspective parameter to your client configuration or query:

const getUserCart = async (req, res) => {
  try {
    const currentUserId = req.userInfo.userId;
    const carts = await client.fetch(
      `*[_type == "carts" && userId == $userId]`,
      {
        userId: currentUserId,
      },
      {
        perspective: 'previewDrafts', // or 'published' depending on your needs
      }
    );
    res.json(carts);
  } catch (error) {
    console.log({ message: "Failed to get user cart" });
  }
};

Note: As of API version 2025-02-19, the default perspective changed to published (previously it was raw). If you need the absolute latest data including drafts, use previewDrafts.

2. Use the CDN bypass option

If you need real-time data and want to bypass the CDN entirely, configure your client with useCdn: false:

import { createClient } from '@sanity/client';

const client = createClient({
  projectId: 'your-project-id',
  dataset: 'your-dataset',
  useCdn: false, // Bypass CDN for fresh data
  apiVersion: '2025-02-19',
  token: 'your-token', // Required for authenticated requests
});

3. Consider using Sanity Functions

If you're building serverless endpoints that need real-time data, consider using Sanity Functions instead of external API routes. They have native integration with the Content Lake and better performance for real-time data access.

Why this happens

When you see updated content in the Studio but stale data in your fetch, it's because:

  • The Studio shows you draft content in real-time
  • Your API queries might be hitting the CDN cache which serves published content
  • The CDN can cache responses for up to 60 seconds by default

Setting useCdn: false or using the appropriate perspective should resolve your issue!

Show original thread
11 replies
are you fetching from cdn?
I don't believe so, it's trying to fetch data being stored by this function:
const updateCart = async (req, res) => {
  try {
    const cartInfo = req.body;
    const { cartItems, totalPrice, totalQuantities } = cartInfo;
    const currentUserId = req.userInfo.userId;

    // Fetch all carts that belong to the current user
    const carts = await client.fetch(
      `*[_type == "carts" && userId == $userId]`,
      { userId: currentUserId }
    );

    // Loop through the carts and update each one
    for (const cart of carts) {
      const { _id } = cart;

      // Update the cart document with the new cart items, total price, and total quantities
      await client
        .patch(_id)
        .set({ cartItems, totalPrice, totalQuantities })
        .commit();
    }
    res.sendStatus(200);
  } catch (error) {
    console.log({ message: "error at updateCart" });
  }
};
and the data looks like this in my desk:

"name": "Drizco Z-Watch",
    "price": 200,
    "quantity": 1,
    "slug": {
      "_type": "slug",
      "current": "drizco-z-watch"
    }
  },
  {
    "_createdAt": "2023-03-31T19:21:36Z",
    "_id": "ab5f9754-5837-4c96-aae9-67cc1a8538c8",
    "_rev": "2Vh7m7t6FPDRFeGM5I3Esj",
    "_type": "product",
    "_updatedAt": "2023-03-31T19:21:36Z",
    "details": "Most affordable earbuds on the market",
    "image": [
      {
        "_key": "ba88e67e8f6d",
        "_type": "image",
        "asset": {
          "_ref": "image-07fd4b12012f56f93ee9c5090a09754b4d8ee9dd-600x600-webp",
          "_type": "reference"
        }
      },

what's your client config look like
I am using a cdn to initially store the images though
does it have cdn: true ?
yes
const sanityClient = require("@sanity/client");

const client = sanityClient({
  projectId: "k0utdl03",
  dataset: "production",
  apiVersion: "2022-03-10",
  useCdn: true,
  token: process.env.NEXT_PUBLIC_SANITY_TOKEN,
});

module.exports = {
  client,
};
change that to false and you should be good
content will be cached on cdn and doesn't get updated for ~10 minutes
good for production but not development
I see, thank you for the help

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?