How to run a Shopify Cart Transform function only when the Theme App Embed is enabled?

I’m using a Shopify Cart Transform function and I want it to run only on the theme where my app embed is enabled.

If the app embed is turned OFF for a theme, the function should not apply any cart transformations.

Since Shopify Functions are theme-agnostic, what is the recommended or best-practice approach to conditionally control the function behavior based on whether the theme app embed is enabled or not?

Any guidance or suggested workaround would be appreciated.

Hi @Ahsan_Ahmed,

You can use cart attributes to achieve this.

  1. With your app embed, maintain a boolean cart attribute e.g. activated_theme.

  2. Query the cart attribute in your Cart Transform Function’s input query e.g.:

query CartTransformRunInput {
  cart {
    activated_theme: attribute(key: "activated_theme") {
      value
    }
    lines {
      # ... other line fields
    }
  }
}
  1. In the logic of your Cart Transform Function, check the value of the cart attribute before performing any operations e.g.:
export function cartTransformRun(input) {
  const activatedTheme = input.cart.activated_theme?.value;
  
  // Only run transform logic if theme_activated attribute exists on cart
  if (activatedTheme !== "true") {
    return { operations: [] };
  }

  // Transform logic here
  return { operations };
}

Let me know if you have any questions about this approach! :slight_smile:

Hi @Paige-Shopify

Got it, Thanks,

I’m confused about one thing mentioned below, could you clarify?

This code was embedded and ran successfully. The issue now is that the user had added a product to the cart but didn’t complete checkout. I turned the embed off, but the cart attribute is still saved and hasn’t been removed.

Once cart attributes are added to a cart, they aren’t removed unless a request to the cart is made to clear them.

To address this your app can have a simple off and on button.
If the off, you can have your app embed set activated_theme to false.
Afterwards the app embed can be toggled off from the theme.

If the theme app embed is turned off, my code won’t run at all. In that case, how can I update or set the cart attribute value to false?

That’s actually why I suggested having an off/on button in your app in an app home page. The cart attribute value can be based on that setting.

If the app embed is turned off before the button is set to off, any active carts with the attribute would still have it set to true until the cart expires or checkout completes.