NextJs, Docker and IP Geolocation
Jorge
Posted on November 9, 2024
These days, I've been working on a solution that would allow us to geolocate users through their IP address, with our NextJs project hosted on AWS ECS in a Docker container.
With the primary focus on geolocating users through their IP address, other challenges emerged, which I will enumerate.
1. AVOIDING THIRD-PARTY CALLS
This point was important because, although there is a wide catalog of services (many free of charge) that offer IP geolocation, I didn't want to depend on a third-party call if possible.
During my research, I found several services that allow you to download a binary file with the ".mmdb" extension, which is the actual database we can use to geolocate IPs.
After completing the investigation I opted for Maxmind. They have many options through which you can download the binary database but I decided to use the geoipupdate automation they offer in their documentation. This allows you to automate the process of downloading and updating the .mmdb
file.
2. PROTECTING LOGIC FROM CLIENT-SIDE
Another key aspect was to leverage Next.js's server-side capabilities to avoid exposing logic on the client side. In current versions, this can be done by either generating a "route handler" or using a "server action". For versions prior to 13, we would need to create our own "API route".
To obtain our users' IP on the server side, we only need the req.headers['x-forwarded-for'] header provided by Next.js. Once we capture their IP, we'll search for its origin in our file using the mmdb-lib node package.
3. PERIODIC AUTOMATIC DATABASE SYNCHRONIZATION
The Maxmind geoipupdate integration was extremely helpful for this purpose. This integration automatically manages the download and update of the file with minimal configuration, requiring only your credentials to be provided.
The main problem I encountered was that within a node:alpine Docker container, I couldn't execute cron jobs with a user other than root. I resolved this by using supercronic, a tool optimized for running your cron jobs inside Docker images. Additionally, it's worth nothing that this tool facilitates the visualization of logs about how the process targeted by the crontab has progressed.
Once this was resolved, I managed to keep a cron job running in the background within the Docker container where my Next.js project is deployed. This cron job periodically checks and updates my binary database file stored within the container's own file system.
FINAL NOTES
In order to have a guide where part of this process can be visualized, I have generated a pre-configured template. In it, we can verify the functionality and observe the minimum necessary configuration:
Posted on November 9, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.