Tmirror

How to fetch IP address using cloudflare workers js


How to fetch IP address using cloudflare workers js

In a Cloudflare Workers script, you can access the IP address of the client making a request through the request object. The IP address can be found in the cf (Cloudflare) property of the request object. Here’s an example of how you can fetch the client’s IP address using Cloudflare Workers and JavaScript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const clientIP = request.headers.get('cf-connecting-ip');
  
  if (clientIP) {
    return new Response(`Your IP address is: ${clientIP}`, {
      status: 200,
      headers: {
        'Content-Type': 'text/plain',
      },
    });
  } else {
    return new Response('Unable to determine your IP address.', {
      status: 500,
      headers: {
        'Content-Type': 'text/plain',
      },
    });
  }
}

In this example, the addEventListener listens for fetch events, and the handleRequest function retrieves the client’s IP address from the cf-connecting-ip header in the request. It then constructs a response with the IP address if it’s available, or provides an error message if the IP address couldn’t be determined.

Remember to deploy this code as a Cloudflare Worker to see it in action. Make sure you have an active Cloudflare account and are familiar with deploying workers through their platform. Also, note that Cloudflare’s features and APIs might change over time, so you should refer to Cloudflare’s official documentation for the most up-to-date information.

comments powered by Disqus