Skip to content

How to create a free IP Lookup Tool using Cloudflare

Posted on:June 8, 2023 at 08:17 AM

IP Lookup tools are incredibly useful for obtaining information about an IP address. In this post, we will walk through creating a free IP Lookup tool using Cloudflare Workers. Cloudflare Workers let you run serverless functions, and they are perfect for this kind of lightweight application.

Prerequisites:

Before you start, you need to have a Cloudflare account. If you don’t have one, you can sign up for free at Cloudflare.

Step-by-Step Guide:

Step 1: Create a Cloudflare Worker

1. Log in to your Cloudflare account.
2. Go to the "Workers" section.
4. Click on the "Create a Worker" button.

You will be taken to the Workers editor, where you can write and deploy your code.

Step 2: Write Your IP Lookup Code

In the editor, you’ll see a script. Replace it with the following JavaScript code:

export default {
  async fetch(request, env) {
    const corsHeaders = {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET,OPTIONS",
      "Access-Control-Max-Age": "86400",
      "Content-Security-Policy": `default-src *;`,
    };
    async function handleOptions(request) {
      if (
        request.headers.get("Origin") !== null &&
        request.headers.get("Access-Control-Request-Method") !== null &&
        request.headers.get("Access-Control-Request-Headers") !== null
      ) {
        // Handle CORS preflight requests.
        return new Response(null, {
          headers: {
            ...corsHeaders,
            "Access-Control-Allow-Headers": request.headers.get(
              "Access-Control-Request-Headers"
            ),
          },
        });
      } else {
        // Handle standard OPTIONS request.
        return new Response(null, {
          headers: {
            Allow: "GET, OPTIONS",
          },
        });
      }
    }

    async function handleRequest(request) {
      console.log(request);
      const data = {
        continent: request.cf.continent,
        country: request.cf.country,
        city: request.cf.city,
        colo: request.cf.colo,
        timezone: request.cf.timezone,
        region: request.cf.region,
        regionCode: request.cf.regionCode,
        asOrganization: request.cf.asOrganization,
        metroCode: request.cf.metroCode,
        postalCode: request.cf.postalCode,
        latitude: request.cf.latitude,
        longitude: request.cf.longitude,
        ip: request.headers.get("cf-connecting-ip"),
      };
      const json = JSON.stringify(data, null, 2);
      return new Response(json, {
        headers: {
          ...corsHeaders,
          "Access-Control-Allow-Origin": "*",
          "content-type": "application/json;charset=UTF-8",
          Vary: "Origin",
        },
      });
    }
    if (request.method === "OPTIONS") {
      // Handle CORS preflight requests
      return handleOptions(request);
    }
    if (request.method === "GET") {
      return handleRequest(request);
    }
    return new Error("Method not supported, use GET or OPTIONS");
  },
};

This code listens for a fetch event and responds with the IP address of the requester and other meta data in JSON format. Cloudflare automatically populates the cf-connecting-ip header with the IP address of the user making the request.

Step 3: Deploy Your Worker

Click on the “Save and Deploy” button. Your worker is now deployed, and you’ll be given a unique URL (e.g., https://your-worker.your-username.workers.dev).

Step 4: Test Your IP Lookup Tool

Open your browser or a tool like curl, and make a request to the URL you were given. You should receive a JSON response with your IP address, like {"ip":"123.456.78.90"}

Further Enhancements

While we’ve created a basic IP lookup tool, you can enhance it further:

  1. Custom Domain: You can configure a custom domain for your worker instead of using the default workers.dev domain.

  2. Rate Limiting: Implement rate limiting to prevent abuse of your service.

  3. Logging and Monitoring: Implement logging and monitoring to keep track of the usage and performance of your IP lookup tool.

Cloudflare Workers provide a powerful and simple way to create an IP lookup tool without the need for managing servers or complex infrastructure. With just a few lines of code, you can have your IP lookup service up and running in no time. As your requirements grow, you can easily scale and add more features. Happy coding!