Created
July 18, 2022 16:12
-
-
Save dbalatero/92b583e69c3dd1111b6cf774fc0f4a7f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
addEventListener("fetch", (event) => { | |
event.respondWith( | |
handleRequest(event.request).catch( | |
(err) => new Response(err.stack, { status: 500 }) | |
) | |
); | |
}); | |
/** | |
* Many more examples available at: | |
* https://developers.cloudflare.com/workers/examples | |
* @param {Request} request | |
* @returns {Promise<Response>} | |
*/ | |
async function handleRequest(request) { | |
const url = new URL(request.url); | |
const { pathname } = url; | |
if (pathname.startsWith("/worker/status")) { | |
return new Response("OK"); | |
} | |
const parts = pathname.split("/", 2); | |
const firstPart = parts[1]; | |
switch (firstPart) { | |
// For /b, billing portal/customer portal | |
// Also /v1 to proxy /v1/billing_portal/sessions/:session URLs | |
case 'v1': | |
case 'b': { | |
return passthroughToOrigin(request, url, "billing.stripe.com"); | |
} | |
// For /c, checkout | |
case 'c': { | |
return passthroughToOrigin(request, url, "edge-checkout.stripe.com"); | |
} | |
default: { | |
return new Response("Wrong prefix!"); | |
} | |
} | |
} | |
async function passthroughToOrigin(request, url, origin) { | |
// Override the host | |
url.host = origin; | |
// Clone a new request from the original to keep all headers. | |
const newRequest = new Request(url.toString(), request); | |
return fetch(newRequest); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment