cart.js fetch response contains no items

Hi everyone

I’m developing an app where the checkout button on the cart page triggers a fetch request to “/cart.js” to retrieve cart items. After adding monitoring functionality, I’ve noticed that sometimes the request response is empty. You can simulate this by executing a fetch request on the cart page via the console when there are no items in the cart.

However, it’s not possible to proceed to the checkout page with an empty cart—or at least it shouldn’t be. I’m trying to understand why this happens. I’ve even implemented a refetch functionality for cases when the returned cart object is empty.

I haven’t been able to reproduce this behavior. Is it possible that items appear in the cart for customers but are actually expired, sold out, or otherwise invalid? Could these items disappear after a page reload, despite being visible initially? That’s my current theory.

Thanks for any insights!

Hi @SergiiB ,

First, you need to retrieve the information of the products in the store. If it’s empty, you can block it from navigating to the checkout page. If there are products but they are sold out, you can fetch the API to get the information of that product and check its status. Everything depends on the workflow of your app.

This is my code to retrieve information and check if the cart is empty

async function fetchCartItems() {
  try {
    const response = await fetch('/cart.js', { cache: 'no-store' });
    if (!response.ok) {
      throw new Error('Something wrongs');
    }
    const cart = await response.json();
    console.log('Cart:', cart);
    if (!cart.items || cart.items.length === 0) {
      console.log('Empty cart, refetching...');
      return await fetchCartItems();
    }
    return cart;
  } catch (error) {
    console.error('Fetch error:', error);
  }
}