How to accurately determine what variant is displayed by default without Liquid Part 2

This is a follow-up to How to accurately determine what variant is displayed by default without Liquid

The recommended solution there was to use webhooks + server-side Storefront API calls to grab Product.selectedOrFirstAvailableVariant but we are re-evaluating this do to the needless amount of processing required for a feature that many shops do not use.

Our thoughts were instead of doing this server-side we can use the AJAX API then do:

variants.find((variant) => variant.available)

It sounds like this is a reliable way to replicate this but not 100% sure.

Of course if that doesn’t work calling Storefront API directly client-side using the @inContent directive and grab Product.selectedOrFirstAvailableVariant there but this is slightly more bloated.

Thoughts?

Hi @sshaw the Ajax expression needs a fallback when every variant is unavailable:

const defaultVariant =
  variants.find(variant => variant.available) ?? variants[0];

The bigger limitation is that the Ajax Product API returns at most 250 variants. If the first available variant is outside that response, adding the fallback won’t help you find it.

For Shopify’s default selection, I’d use your client-side Storefront approach: request selectedOrFirstAvailableVariant without selectedOptions, selecting just id if that’s all you need. Running that lookup only when the feature is used avoids maintaining the value through background webhook processing. You can use @inContext to supply the relevant market context.

That ID-only lookup also supports tokenless Storefront access, so it doesn’t require the additional Storefront permission you mentioned in the original thread.

Thanks. One question: how does @inContext differ from specifying a locale in the AJAX API URL?

Well, I guess for locale they’re the same but with country one will get market-specific availability that won’t be available via the AJAX API?

Ajax can reflect country-specific availability too. Using window.Shopify.routes.root preserves the Online Store’s current language and country. Availability can account for stock at locations that ship to that country, depending on the shop’s inventory settings.

With Storefront, you supply the country explicitly through @inContext. You can use window.Shopify.country for that without Liquid, and omit language when you’re only requesting id. I recommended Storefront for selectedOrFirstAvailableVariant and to avoid Ajax’s 250-variant limit.