addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
// Clone the request to prevent issues with body being already read
const requestClone = request.clone()
// Get the original URL
const url = new URL(request.url)
// Modify the path to remove '/ss' prefix
const newPath = url.pathname.replace(/^\/ss/, '')
// Construct the new URL
const targetUrl = 'https://server-side-tagging-XXXXXXXXXXX.us-central1.run.app' + newPath + url.search
// Create a new request to the target URL with added headers
const modifiedRequest = new Request(targetUrl, {
method: requestClone.method,
headers: new Headers({
...Object.fromEntries(requestClone.headers),
'X-Forwarded-Host': 'ss.YOURDOMAIN.com' // Add the X-Forwarded-Host header
}),
body: requestClone.body,
redirect: 'follow'
})
// Fetch the response from the target URL
const response = await fetch(modifiedRequest)
// Return the response back to the client
return response
}