How to make simple Geolocation service
If you ever tried to make a Geo-location service (e.g. define a user country based on user IP address), most likely you heard about MaxMind.
MaxMind - is probably one of best companies who provides Geo IP databases and services.
However, there is a number of limitations: if you're making a side-project, most likely you do not want to pay extra $$$ for geolocation services. And for this case MaxMind offers GeoLite2 database, however you'll be in charge of hosting this database on your server and making regular updates of the database. You also need to make sure your project is compliant with MaxMind's License.
Why to use Cloudflare Workers instead of AWS Lambda?
In this particular example, I needed a simple geo-location service which will be used in embeddable javascript code (similar to Google Analytics or other tracking service), so the response time is quite crucial.
In my first attempt I tried to use Serverless framework to host simple geo-location function on AWS Lambda (this function uses MaxMind GeoLite2 database). However, I quickly realized that the response time isn't what I've expected - on average the response took somewhere between from 200ms to 500ms. So I started looking for other options.
So, I thought - if I could not host it on AWS Lambda, where else I could host my serverless function? The next service I tried - is Cloudflare Workers. I created a simple function to test the reponse time, and it was really impressive - on average it was between from 30ms to 80ms, I've got almost x10 better performance in comparison to AWS.
However, this solution had one really big caveat - MaxMind GeoLite2 database does not work on Cloudflare Workers due to some runtime limitations.
MaxMind alternative
And then I thought - hey, wait a second, as Cloudflare provides DDoS protection services, they might provide some interesting features in Cloudflare Workers. And after exploring their documentation, I realized that the Request
object in function have an access to cf
object, which contains some useful information about the visitor, including visitor's country!
That's exactly what I was looking for, within a few dozens of lines of code I got my geolocation function up and running.
The source code
If you haven't worked with Cloudflare before, you need to signup at Cloudflare.com and go to Workers directory.
Then, create a new worker with the following source code:
Then you can start making requests to your Worker's endpoint.