I’m building a Shopify theme app extension, and as part of my extension’s functionality, I want to track cart changes and send them to my backend.
This is the way I’m currently catching cart events:
interceptCartRequests() {
const originalFetch = window.fetch;
const self = this;
window.fetch = async function (...args) {
const response = await originalFetch.apply(this, args);
const url = args[0]?.toString() || "";
if (url.includes("/cart/add") || url.includes("/cart/update") || url.includes("/cart/change")) {
setTimeout(() => {
self.checkCartChanges();
}, 100);
}
return response;
};
}
async checkCartChanges() {
const cartToken = await this.getCartToken();
...
}
async getCartToken() {
try {
const response = await fetch("/cart.js");
if (!response.ok) throw new Error("Failed to fetch cart");
const cart = await response.json();
return cart.token;
} catch (error) {
utils.error("Error fetching cart token:", error);
return null;
}
}
As you can see above, I’m using the Ajax API for fetching the cart GID from within my extension.
If you’re familiar with the way the cart GID is handled, then you know that until I add any product to the shopping cart, each time I’ll call the /cart.js API, I’ll get a new temporary ID for the cart, something like b3d1fd695ce07e26efeb33ae82f8aec1z.
This if of course until I add a product to the cart, then I’ll get a constant cart GID, something like hWN2cUbDCg4AXclftJnh761L?key=285d69273147954feed138de29d4f8b7.
The thing is that the GID won’t be set until some event which I can’t keep track of. I mean that I try to fetch /cart.js after adding to cart was completed, but I’ll still get the temporary cart ID, but if I’ll fetch the /cart.js a few seconds later, I’ll get the constant GID.
I want to fetch the constant cart GID as soon as the item was added to the cart. How would you recommend me to do so?