Created
August 21, 2024 15:54
-
-
Save marckohlbrugge/dbb309efb205db1a5ea9944c1ded728b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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