Skip to content

Instantly share code, notes, and snippets.

@marckohlbrugge
Created August 21, 2024 15:54
Show Gist options
  • Save marckohlbrugge/dbb309efb205db1a5ea9944c1ded728b to your computer and use it in GitHub Desktop.
Save marckohlbrugge/dbb309efb205db1a5ea9944c1ded728b to your computer and use it in GitHub Desktop.
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
// Modify the request to point to the Google Tag Manager endpoint
url.hostname = env.GTM_HOST;
// Create a new headers object based on the original request headers
const modifiedHeaders = new Headers(request.headers);
// Add the geolocation header if available
if (request.cf && request.cf.regionCode) {
modifiedHeaders.set('X-CfIpCountryRegion', request.cf.regionCode);
}
// Override the Host header to the Google Tag Manager endpoint
modifiedHeaders.set('Host', env.GTM_HOST);
// Create a new request with the modified URL and headers
const modifiedRequest = new Request(url.toString(), {
...request,
headers: modifiedHeaders,
});
// Fetch the modified request
return fetch(modifiedRequest);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment