Skip to content

Instantly share code, notes, and snippets.

@cicku
Created July 6, 2025 14:24
Show Gist options
  • Select an option

  • Save cicku/f57e31cc262e2fcb54976faa5675d25a to your computer and use it in GitHub Desktop.

Select an option

Save cicku/f57e31cc262e2fcb54976faa5675d25a to your computer and use it in GitHub Desktop.
Cloudflare Worker for SaaS provider routing without custom origin server
// SaaS provider creates different subdomains to handle traffic of different eyeball domains
// Get rid of https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/start/advanced-settings/custom-origin/
const ORIGINS = {
'a.com': 'a.cicku.me',
'b.com': 'b.cicku.me',
'c.com': 'c.cicku.me',
'd.com': 'd.cicku.me',
'e.com': 'e.cicku.me',
'f.com': 'f.cicku.me'
};
let target = ""
let response = ""
async function handleRequest(request) {
const url = new URL(request.url);
if (url.hostname in ORIGINS) {
target = ORIGINS[url.hostname];
url.hostname = target;
response = await fetch(url.toString(), request);
}
else {
response = await fetch(request);
}
const newResponse = new Response(response.body, response);
// add a header for debugging
newResponse.headers.append('x-origin-server', '1');
return newResponse;
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment