Hrithwik Bharadwaj
Hrithwik Bharadwaj

Hrithwik Bharadwaj

Use Cloudflare Workers as a Reverse Proxy

Use Cloudflare Workers as a Reverse Proxy

Hrithwik Bharadwaj's photo
Hrithwik Bharadwaj
ยทMar 15, 2022ยท

6 min read

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Table of contents

Reverse Proxy / Rewrites allow us to serve content from different hosts/websites to our domain.

For example, this article you are reading, is on blog.hrithwik.me which is essentially a Reverse proxy / Rewrite of hrithwik.hashnode.dev.

So you get the idea, this can be super useful for building SAAS with custom domains, Serving your blog from subdomain to subdirectory, or even serving content from a no-code website builder to your own domain for *FREE.

Well, there are a plethora of other things you can do with Cloudflare workers as a Reverse Proxy, but here are a few things this article covers.

(if you have worked with next.js, this is similar to next.js rewrites)

Things covered in this article

  • Getting Started with Cloudflare Workers
  • Simple Reverse Proxy/ Rewrites Example with Cloudflare workers
  • How to Block Few words from your Articles in a few regions with Cloudflare Workers

What is Cloudflare Workers and Why use it?

For starters, Cloudflare Workers is a serverless architecture that can run JavaScript code on the edge.

That means you don't need to manage the infrastructure and scale it based on the traffic, also means your code is distributed at over 117+ countries and runs in the nearest location of the request with almost zero delay/cold start and is super quick (max 100ms).

It uses V8 Engine under the hood to run JavaScript but not a complete node.js environment so not all npm packages might work. But for most of our use case, this is more than enough.

Also, Cloudflare is super generous with its FREE Plan, which gives us 100K requests/day ๐Ÿ˜ฏ

So in short, It's lightweight, fast and free to get started with.

Things you will need

  • Basic knowledge of JavaScript and NPM modules.

  • A Cloudflare Account ,

  • Wrangler CLI, which makes our life easy while working with Cloudflare workers. Here is how you can install it globally.

npm i @cloudflare/wrangler -g

Getting Started with Cloudflare Workers

Ensure you have installed the Wrangler CLI

    • Run wrangler generate <project-name> in your command prompt.

(This will create a bunch of files in the directory and the most important ones are wrangler.toml, index.js and package.json to be honest.)

bunch.JPG

  1. Run wrangler login (Accept the consent after logging in and you are done.)
  2. Run wrangler dev , which will start the local server and when you visit it you must get "Hello worker!" Response

screely-1647180093389.png

Now Let's get to the meat of the topic

Cloudflare Workers as a Reverse Proxy / Doing Rewrites using Cloudflare Workers

Rewrites as the name suggests, allow us to proxy a website to our domain, for example,

Let's say I want content from this website something.site on my personal domain something.com,

I can write some small piece of code, which will fetch content from something.siteand then show that on something.com whenever someone visits something.com

here is how you can make this work.

paste the below code in your index.js and replace example.com with the domain you want to proxy / fetch content from.

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const url = new URL(request.url);
  url.hostname = 'example.com';
  const data = await fetch(url.toString(),request);
  return data;
}

addEventListener listens to every request and passes it to our handleRequest Function. Here we are creating a new URL object and replacing its host with example.com. Now we fetch the data from the site(This is very similar to the fetch browser API ) with the original request headers etc and return the data.

I will be using my domain richurl.tech instead of example.com

image.png

and yay, it's working ๐ŸŽ‰

Note: If you observe the network tab, on every reload you are making 35-50 requests, which means that you will exhaust your Free plan if you get 3000 -2000 requests per day.

image.gif

I still feel the FREE plan is more than enough for most of your needs but if you want more you can look at the pricing here

How to Block Few words from your Articles in a few regions with Cloudflare Workers

If you want to create a cuss free mirror of a website, here is how you do it.

I will be using this website as an example whatthefuck.is/memoization . (Great Post by the way)

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const url = new URL(request.url);
  url.hostname = 'whatthefuck.is';
  const data = await fetch(url.toString(),request);
  // Read response body.
  let text = await data.text();
  // Modify it.
  const cussWordRegex = /fuck/g;
  let modified = text.replace(cussWordRegex , "fork");
  // create a new response and return it
  return new Response(modified, {
    status: data.status,
    statusText: data.statusText,
    headers: data.headers
  })
}

the first three lines of code inside the handleRequest function remain the same, that is we are fetching content from another host website, but instead of straight out returning the response, we modify a few things and create a new response and send it.

(We get the HTML text data and replace cuss words with something else and send the response.)

image.png

Works like a charm. Here is a playground if you want to play around with this

for some reason if you decide not to to show cuss words only for certain regions like India or Korea (just example lmao) , here is how you do it

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const url = new URL(request.url);
  url.hostname = 'whatthefuck.is';
  const data = await fetch(url.toString(),request);

  const country = request.cf.country;
  const cussFreeCountries = ['IN', 'KP'];

  if(cussFreeCountries.includes(country)){
    let text = await data.text();
    const cussWordRegex = /fuck/g;
    let modified = text.replace(cussWordRegex , "fork");
    return new Response(modified, {
      status: data.status,
      statusText: data.statusText,
      headers: data.headers
    })
  }

  return data;

}

Cloudflare workers also allow us to identify countries using request.cf.country, so we can probably keep an array of not allowed countries and replace cuss words if the request is coming from those countries otherwise just return the same original data.

So you get it, we are kind of intercepting data by fetching data from the original host and then modifying a few things and sending the response. You can even add styles and some other js code too if you want some additional functionality in your proxied site.

Let's Publish it

Run this command wrangler publish and this will publish your code to a subdomain of Cloudflare,

Here is how you add Cloudflare workers to your custom domain.

Step 1 - Add a route for your workers after selecting the domain in the dashboard

image.png

Here I am using my service paytm-tap (It's the project name), but you can choose the name of your project

image.png

Step 2 - Point your domain to a random IP address in Cloudflare

image.png

and it's done, your domain now runs Cloudflare workers ๐ŸŽ‰


That's it folks, a small introduction to Cloudflare worker as a reverse proxy/rewrites.

There are several other use cases like using blog.domain.com as a reverse proxy at domain.com/blog etc which I will cover in the future if time permits.

I think if you play around with workers a little bit, you will figure out this by yourself too.

I do some random shitposting on Twitter, so let's stay in touch there.

If you have doubts or struck somewhere while using Cloudflare workers there are always people who help you here on the Cloudflare Discord

Did you find this article valuable?

Support Hrithwik Bharadwaj by becoming a sponsor. Any amount is appreciated!

See recent sponsors |ย Learn more about Hashnode Sponsors
ย 
Share this