Magento – GeoIp-based default currency selection behind Varnish

currencyvarnish

I want a store to intelligently choose a default currency based on the customer's IP using GeoIP when they first visit (with no preselected currency cookie). The store is behind Varnish using Nexcess's excellent Turpentine extension.

The extension handles currency fine as long as the standard Magento currency cookie is set on a given request.

My thoughts at this stage are:

  1. Add VCL into the Varnish config to do the GeoIP lookup (in C) and set the cookie on the inbound request, if it's not already set, of course.
  2. Add a per-user cached block that does the lookup and sets the cookie (though this would then not apply on the first page load)

Am I missing an obvious technique – maybe some client-side JS to a non-varnish-cached URL path that makes the determination?

Does anyone know the best way to do this?

Best Answer

We've got something like this running in production (we're enabling or disabling add to cart and pricing depending on the customer's location).

We built and installed the "Varnish GeoIP module" from https://github.com/leed25d/geoip-vmod ... This sets a "X-GeoIP" header in each request that reaches Magento indicating the user's country. Within Magento you need to detect this header and customise the content as required.

The final problem to overcome is that Varnish will cache the generated page and serve it to all customers regardless of their country. You could "turn off" caching for that page, but performance suffers, so that's not ideal either. Our solution was to send a "Vary" header in our HTTP response, which tells Varnish to cache different objects for different values of the X-GeoIP header, so we have a different page cached for each visitor's country.

One of my colleagues at Aligent has created a Magento module which contains a helper to fetch the country code from the X-GeoIP header (with fallback to IP if it's not present, which is useful for development), and an observer to send the "Vary" header. We've open sourced the module, check out https://github.com/aligent/Aligent_GeoIP if you want the implementation detail.

Related Topic