Useful Cloudflare Workers

Home 📂 Blog Posts

Published at: 2020-02-06 22:46:28 +0000


Cloudflare offers a feature called "Workers" which lets you create proxies to your content. This is useful when you have an API key to use an API, don't want to use port 80 on your server, or have firewall IP restrictions. Here are two configs I regularly use.


Cloudflare publishes their list of IP addresses here so you know what to put in your firewall.


This first one just proxies content to a server and port.


async function handleRequest(request) {

  request = new Request(request);

  const URL = request.url.replace(/https:\/\/contact.max.town\//, "http://contact-server.max.town:1234/");

  return fetch(URL, request);

}


addEventListener('fetch', event => {

  event.respondWith(handleRequest(event.request))

})


This 2nd config lets you proxy to an Amazon API Gateway, but similarly could be used to proxy an Azure Function App.


async function handleRequest(request) {

  request = new Request(request)

  const country = request.headers.get('cf-ipcountry')

  request.headers.set('country', country)

  request.headers.set('x-api-key', '123412341234')

  const URL = "https://ABCD1234.execute-api.us-east-1.amazonaws.com/default/API"

  return fetch(URL, request)

}

addEventListener('fetch', event => {

  event.respondWith(handleRequest(event.request))

})





Generated by Max Space

odllVa/fA10h/kLCYGF2y2
/awenS4UUAHOIT/8/0Pgc=