このページは現在英語版のみで提供されており、日本語版も近日中に提供される予定です。ご利用いただきありがとうございます。

Customization Based on Client Geo Location

This example captures incoming HTTP requests and provides customized welcome messages and geo location (latitude and longitude) information based on the country where the client is located. It can be used for offering global personalized customization experience to users.

Sample Code

// Add a fetch event listener, which is triggered when a request is incoming. It uses the handleRequest function to handle requests and return responses.
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
function handleRequest(request) {
// Get the country code provided by EdgeOne.
const countryCode = request.eo.geo.countryCodeAlpha2;
// Select the corresponding language and welcome message based on the country code.
let responseText;
switch (countryCode) {
case 'CN': // China
responseText =`Hello user from China! Your latitude and longitude are ${request.eo.geo.latitude},${request.eo.geo.longitude}`;
break;
case 'KR': // South Korea
responseText = `한국의 사용자님 반갑습니다! 당신의 위도와 경도는 ${request.eo.geo.latitude}와 ${request.eo.geo.longitude}입니다.`;
break;
case 'DE': // Germany
responseText = `Willkommen in Deutschland! Ihre Breiten- und Längengrad sind ${request.eo.geo.latitude} und ${request.eo.geo.longitude}.`;
break;
case 'US': // USA
responseText = `Hello from the USA! Your latitude and longitude are ${request.eo.geo.latitude} and ${request.eo.geo.longitude}.`;
break;
default: // Respond in English by default in other cases.
responseText = `Welcome to our service! Your latitude and longitude are ${request.eo.geo.latitude} and ${request.eo.geo.longitude}.`;
break;
}
// Return a response.
return new Response(responseText, {
headers: {
'Content-Type': 'text/plain;charset=UTF-8'
}
})
}

Sample Preview

In the address bar of the browser, enter a URL that matches a triggering rule of the edge function to preview the effect of the sample code. If the client of the current request URL is located in China, the browser will respond with the welcome page for China, as well as the latitude and longitude of the client geo location.


Related References