Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reggeenr/5567290793a1a455984bc6646fa79ca8 to your computer and use it in GitHub Desktop.
Save reggeenr/5567290793a1a455984bc6646fa79ca8 to your computer and use it in GitHub Desktop.
This code snipped can be used to create a Cloudflare Edge Function that directs all requests to an IBM Cloud Code Engine application
addEventListener('fetch', (event) => {
    const mutable_request = new Request(event.request);
    event.respondWith(directRequestToCodeEngineApp(mutable_request));
});
async function directRequestToCodeEngineApp(request) {
    // FQDN of the Code Engine application that should receive the traffic
    const targetHost = '<app-name>.<randomcharacters>.<region-name>.codeengine.appdomain.cloud';
    
    try {
      const url = new URL(request.url);
      // let the code engine know what origin the request came from
      request.headers.set('X-Forwarded-Host', url.hostname);
      request.headers.set('host', targetHost);
      // override the hostname
      url.hostname = targetHost;
      // enforce HTTPS towards Code Engine
      url.protocol = "https:";
    
      // pass the request to the application running on Code Engine
      return await fetch(url.toString(), request);
    } catch (error) {
      // in case of an error, play the regular request
      console.log(`Failed to pass reqzest to '${targetHost}'`, error);
      return await fetch(request);
    }
}
@carlosbittrich
Copy link

carlosbittrich commented Jun 14, 2022

My original comment was that "This snippet only support requests that don't include a body. It fails for patch and post." but I don't know what I changed but it is working now without any change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment