/// <reference types="@fastly/js-compute" />
addEventListener('fetch', (event) => event.respondWith(handleRequest(event)));
async function handleRequest(event) {
const request = event.request;
const client = event.client;
if (client != null && client.geo != null) {
const lat = client.geo.latitude;
const long = client.geo.longitude;
// Using 1 decimal here produces a square of approximately 11km across
// (123 square kilometers), or about 12 million unique locations on the
// Earth's surface (albeit most of them will be ocean)
const gridID = lat.toFixed(1) + ',' + long.toFixed(1);
// We assume caching content is performed upstream based on the Grid ID
// Create Grid ID headers for the upstream request to origin
const upstreamHeaders = new Headers({
'grid-id': gridID,
'geo-city': client.geo.city
});
// You can send the modified request upstream to the origin
// using the custom headers with the Grid ID information
const upstreamRequest = new Request(request, { upstreamHeaders });
// return fetch(upstreamRequest, {
// backend: "example_backend",
// });
// For this example, we will just send the
// GridID as a response back to the client
return new Response(
'Grid ID: ' + gridID + '. Nearest city: ' + client.geo.city,
{ status: 200 }
);
}
return new Response('Could not resolve geo location', { status: 200 });
}