Obtaining Client IP Address

Since the front end cannot directly obtain the client IP address, it's often necessary to obtain the client IP address through the server side or third-party services in multiple business scenarios. The client IP address is obtained in this example through client IP header EO-Client-IP activated in the Rule Engine, and assembled into data in the form of JSON to respond to the clients, which succeeds in obtaining client IP address by the use of Edge Function.

Sample Code

function handleRequest(request) {
  // Obtain the client IP through the EO-Client-IP header
  const ip = request.headers.get('EO-Client-IP') || '';
  // Respond with JSON data
  return new Response(JSON.stringify({ ip }), {
    headers: { 'content-type': 'application/json' },
  });
}

addEventListener('fetch', event => {
  event.passThroughOnException();
  event.respondWith(handleRequest(event.request));
});

Sample Preview

Firstly, activate the client IP switch of the domain name that needs to trigger the Edge Function and set the header name as EO-Client-IP in the Rule Engine configuration.

22.1.png

Once the configuration is effective, enter a URL (such as https://example.com/ip) which matches the trigger rule of the Edge Function in the address bar of the browser on both the PC and mobile terminal to obtain the client's IP address:

22.2.png

Related References

  1. Runtime APIs: Fetch
  2. Runtime APIs: Response