Laravel Tutorials

Geocoding with Cloudflare

Published Updated
Geocoding with Cloudflare image

I like to offer Laravel Shift for "20 bucks". But $20 may be more or less depending on where you live. So if you're in a country where the value of your dollar is 50% less than USD, I offer purchasing power parity.

To determine the country you live in, I use a geocoding service. One that translates your IP address to your country. If that country is one where I offer purchasing power, you see a banner at the top to activate your discount.

Now, I've been on a quest to make the laravelshift.com as fast as possible using Cloudflare. Along the way I stumbled upon another one of their free services - geocoding. Cloudflare appends a country header to the request before forwarding to your web server.

The CF-IPCountry header is a 2 character country code. For example, US or UK. In my case, I was able to use this header directly. Then map the code to a country name to check for purchasing power.

This allowed me to do two things. First, it allowed me to remove hundreds of lines of code. Second, it allowed me to cache the page.

Since the page previously had logic to check the request headers, it was too dynamic to cache. Instead, I sent an API call to check the country after the page load.

All of this was not only more code, but an additional, albeit lightweight, request.

But since this header is available at the Cloudflare level, I was actually able to create a transformation rule. Within it I could check the country code and append a query string to the request.

This allows me to cache two versions of the page. One for the default page display, and another displaying the purchasing power banner.

Again, since this is opt in, your location header is double checked before activating the discount.

If you're interested in seeing the full code refactor, I livestreamed this for my Confident Laravel testing course..

If you're interested in making your page load super fast, check out my video course Fast Laravel.

Sponsored

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article