Cloudflare Workers

Converted https://socialrecommendator.com to a statically hosted, serverless cloud function invoking, single page app, from the single page php it was for 10 years. Mixing two cloud platforms, Firebase for the static hosting, and Cloudflare Workers for the cloud function (in stead of a Firebase Function). Still using old-school jQuery though.

Yes I could use a Firebase Function, but I wanted to use Cloudflare Workers. Firebase hosting is free, but Cloudflare hosting isn’t. And I wanted to a try cross platform integration.

Cloudflare Workers is pretty straightforward to setup and call (with the regular CORS caveats). It’s surprisingly simple to figure out and get working. There aren’t three dozen of options to pick from. I was genuinely surprised that I got it to work from the first time. There’s a Playground to play around with Workers.

Getting CORS to work (for my own domains), in the handleRequest(request) Cloudflare function:

// array of my hostnames
const MY_HOSTNAMES = ['socialrecommendator.com',  'socialrecommendator-au.web.app', 'socialrecommendator-au.firebaseapp.com']; // custom domain + all Firebase domains
let url = new URL(request.url); 
let referer = request.headers.get('Origin');// origin should be one of my hosts
let refererHost = referer ? new URL(referer).hostname : new URL(request.url) ; // this in case if no referer, when I try this on the Cloudflare console
// only set CORS header for my hosts, so that request would fail for other hosts
if (MY_HOSTNAMES.includes(refererHost)) {
    response.headers.set('Access-Control-Allow-Origin', url.protocol + '//' + refererHost); // this should match the Origin header passed in to succeed
    response.headers.set('Access-Control-Allow-Credentials', false);
  }