An automatic gift requires two separate decisions: which item belongs in the cart, and what makes that item free or discounted. Adding a product through JavaScript does not change its Shopify price or enforce the promotion at checkout.
Define the promotion rules
Specify the qualifying products or spend threshold, eligible markets, maximum gift quantity and what happens when the gift is unavailable. Decide whether customers can remove the gift and whether adding it manually should receive the same discount.
Choose a supported discount or application approach for the pricing rules. Storefront code can manage presentation and cart additions, but it should not be the only mechanism controlling eligibility.
Integrate with the current cart
Shopify's Ajax Cart API supports adding variants to a customer's cart using locale-aware URLs. A custom integration must work with the theme's cart drawer, normal cart page and other add-to-cart paths.
Prevent repeat additions when the cart refreshes. Reevaluate the rule when quantities change or qualifying items are removed. Handle inventory errors and keep the cart total and gift message consistent with the final discount result.
Test the complete purchase path
Test a qualifying cart, a nonqualifying cart, crossing the threshold in both directions and removing the gift. Include accelerated checkout, returning sessions and any subscription or bundle products used in the store.
Make the promotion terms visible. Do not silently add a paid product or preselect an optional charge. If a special packing or fulfillment step is required, confirm that the warehouse receives the information it needs.
For complex eligibility or connections to other systems, use a properly supported application rather than a fragile snippet copied into the cart template.
References
Put this into practice.
Minion builds Shopify promotion and cart functionality with coordinated storefront behavior, pricing rules and fulfillment requirements.