How to Show Unique Content on Shopify Pages Based on Customer Location

Find the geolocation of the current customer in Shopify without using an app or any third-party service.

If there is one thing the pandemic has thought us, it is that we live in a truly globalized world. Cross-border commerce has seen a phenomenal growth in the past few decades and the challenges of doing business across multiple markets have been significantly reduced.

While ecommerce has enabled any business to offer their products and services to customers in any part of the world, there has also been a lot of attention lately on customer privacy with regulations GDPR or CCPA.

If an online store is setup to serve multiple locations, for example the United States and the European Union, it is very likely that different content may need to be served depending on the location of the current visitor. For example, displaying a special cookie consent banner may be required if the customer is based in the EU, or a “Free Shipping” message may only be relevant to US customers. Perhaps, one of the most popular location-based feture is the option to show the store prices in the local currency.

To achieve this level of customization, we need to be able to geolocate the customer, which is normally determined based on their IP address. In the Shopify theme templates, we can use JavaScript and utilize the browsing_context_suggestions endpoint:

<script>
  fetch('/browsing_context_suggestions')
    .then(response => response.json())
    .then(data => console.log(data.detected_values.country));
</script>

This will return an object that contains the country code and the country name of the customer:

{
  handle: 'US',
  name: 'United States'
}

With that, we can use the handle to conditionally show or hide any country-specific information on the storefront, including at Checkout.

Please note the browsing_context_suggestions geolocation endpoint is not officially documented and while it is available on all Shopify stores (all plans), its behavior may change without notice in the future.

Thanks for reading! Would love to hear any thoughts or questions you may have about this article. Feel free to reach out @allthings_c on Twitter.