Worker GeoIP from custom IP

I have been playing around with cloudflares geolocation data in a worker.

Its simple to get the data from the cf object in the request. Eg:

    const countryCode = request.cf.country
    const continent = request.cf.continent
    const latitude = request.cf.latitude
    const longitude = request.cf.longitude
    const postalCode = request.cf.postalCode

However, I am wondering if there is a way to populate this data with a given IP address? So I sent an IP as a parameter and the worker is able to perform this lookup and respond with the data for that IP?

Edit: I’ve tried to hack something together:

Created a second worker that tried to make use of adding X-Real-IP which according to another post, overrides the CF-Connecting-IP automatically by Cloudflare. The idea here was I could hardcode another IP address and have my other worker return the data based on that new IP.

async function handleRequest(request) {

    const headers = new Headers(request.headers)
    headers.append("X-Real-IP", "23.81.0.59")

    const newRequestInit = {
      method: "GET",
      redirect: "follow",
      headers: headers,
    };
    const attrs = new Request(request, newRequestInit);
    const newRequest = new Request(
        "https://example.net/test",
        attrs
    );
    return fetch(newRequest);

}

Sadly it doesn’t work. What is returned is (IP of the first Cloudflare data center) - but indeed there is some magic going on by replacing both

"ip": "2a06:98c0:3600::103", // request.headers.get("CF-Connecting-IP")
"ip2": "2a06:98c0:3600::103", // request.headers.get("X-Real-IP")

Its also worth noting the data from the geolocation CF request object (eg request.cf.country and request.cf.postalCode), is actually from my own IP location, not the Cloudflare data center.

Can anyone think of a way I can get the geolocation data from a provided IP address?

I don’t believe that you will be able to populate that data with a given IP address.
With workers, the cfproperties object is generated by Cloudflare when they receive a web request with the information.

You probably want something like the MaxMind GeoIP API.

2 Likes

I don’t think CF support custom query IP. It is not what it should be doing.

You can integrate 3rd party API such as IP2Location into Worker. It also has a local database. However, it might be slowing down the Worker start time.

CF use maxmind already - https://support.cloudflare.com/hc/en-us/articles/200168236-Configuring-Cloudflare-IP-Geolocation#12345683 - so im trying to find a way without reusing it.

More looking for a hacky way to put this together but because the cfproperties is locked, its not looking very possible.

You are looking at this as an IP address to country lookup. It is actually a HTTP request to country lookup. Pass a HTTP request to Cloudflare and the lookup will work as expected. :smile: