请选择
Edge Developer Platform
  • Edge Functions
    • Overview
    • Getting Started
    • Operation Guide
      • Function Management
      • Function Trigger
    • Runtime APIs
      • addEventListener
      • Cache
      • Cookies
      • Encoding
      • Fetch
      • FetchEvent
      • Headers
      • Request
      • Response
      • Streams
        • ReadableStream
        • ReadableStreamBYOBReader
        • ReadableStreamDefaultReader
        • TransformStream
        • WritableStream
        • WritableStreamDefaultWriter
      • Web Crypto
      • Web standards
      • Images
        • ImageProperties
    • Sample Functions
      • Returning an HTML Page
      • Returning a JSON Object
      • Fetch Remote Resources
      • Authenticating a Request Header
      • Modifying a Response Header
      • Performing an A/B Test
      • Setting Cookies
      • Performing Redirect Based on the Request Location
      • Using the Cache API
      • Caching POST Requests
      • Responding in Streaming Mode
      • Merging Resources and Responding in Streaming Mode
      • Protecting Data from Tampering
      • Rewriting a m3u8 File and Configuring Authentication
      • Adaptive Image Resize
      • Image Adaptive WebP
      • Customize Referer restriction rules
      • Remote Authentication
      • HMAC Digital Signature
      • Naming a Downloaded File
      • Obtaining Client IP Address
    • Best Practices
      • Adaptive Image Format Conversion via Edge Functions

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.
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});

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' },
});
}

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.

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:


Related References