How to serve *any* website from your own domain (for free!)
Tags: javascript, webdev, beginners, tutorial
Published: 2022-08-13 23:10:00


Have you ever wanted to white-label a website, like display it on your own domain? Or have you wanted to remove a watermark from a website that asks for premium (for edu. purposes ofc.)?

Well, this guide contains everything you need to know to proxy a website/webpage on your custom domain/subdomain! Let's just get into it! 😃

### 🔥 The Backstory (reading optional)

A few months ago, I got my own domain from Google, and have been putting up things on it for a long time. Though, when it comes to social media, I wanted to show a links-in-bio page, not my personal portfolio page.

![Google Domains](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ro1hvvruq70nxmh1dv9f.png)

I looked into some solutions. Found a few websites like short.io that allow you to shorten links and make them visible on your domain base, but they're paid and provide little room for customization. And the ones that did provide awesome features were mostly paid.

So I was left with no choice but to go with the standard-solution: mainstream websites like [bio.link](https://bio.link) or Linktree[https://linktr.ee]. I got my links up on it, customized it to just how I wanted, and it looked really cool.

![My Bio-Link Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/smn3hogd19rz2tfpzsb3.png)

But since I consider myself somewhat of a perfectionist (an understatement, sometimes), and like to bring something unique to the table, I thought about a way to serve the bio-link page on my own domain. 

### ⚖️ But why? A few pros and cons

There are a few 👍 **pros** to hosting a domain! Just to name a few, for me, it was to ability to:

- Makes your link-in-bio page **look unique**: Unlike pages that are bio.link/username, the custom-domain page looks very professional, just like how your portfolio on `youdomain.dev` looks better as compared to `3p-domain.vercel.app`
- **Have total control over anything served over the domain**: Remove watermarks or modify existing content pretty easily!

Cloudflare Workers' specific pros:

- **Analytics** - Cloudflare tracks every request through its proxy, so you could have a direct idea about where your domain visits are coming from, and how they're reaching your website.
- **Caching (Faster loads)** - Cloudflare also caches every request that goes through its DNS proxy, so a slow SPA could easily benefit on subsequent requests from the same user, right out of the box (though it's disabled by default)
- **Increased Uptime**, even when the **source is down**: In case the source website goes down for a short time, the content served over the domain would still work flawlessly, given that it was recently cached.
- **Load Balancing** - You could randomly fetch from 2-3 different sources and get a very basic version of load balancing.
- **Bypass account's free limits** - For example, if you have 2-3 accounts on Vercel hosting the same exact website, you could easily modify the worker's code to randomly fetch from any one of them. This way, you could evenly distribute the data usage between the accounts and not hit the free-account limit on the source website (though this might be against the fair use policy).

👎 **Cons**

It's important to note the downsides of this as well

- **Might not work on every website** - Well-engineered web-apps like Google's auth platform could easily detect if the receiver (in this case, Cloudflare's servers), are the end users of the request. 
This way, they could prevent kind-of man-in-the-middle attacks. But 99% of the websites won't have problems like these.
- **Adds an extra layer** - Though this is pretty unnoticeable, since the responses are un-cached, but basically, since all the data goes through a third-party (Cloudflare), the resource per request usage also increases.
- **Could get pretty expensive (sometimes)**: If your usage stats are out of the roof, and you get more than 100k request per day, subsequent users could face errors if you're on the free plan, till the quota gets reset.

But hey, for light usage and very typical use-cases, chances are that these cons won't matter. In fact, with features like caching and simple analytics, the pros would certainly outweigh the cons.

### 🙋‍♂️ But what is 'Cloudflare Workers'?

![Cloudflare workers](https://i.ytimg.com/vi/48NWaLkDcME/maxresdefault.jpg)

Glad you asked! According to [Workers' docs](https://developers.cloudflare.com/workers/)

> 'Cloudflare Workers' provides a  [serverless](https://www.cloudflare.com/learning/serverless/what-is-serverless/)  execution environment that allows you to create entirely new applications or augment existing ones without configuring or maintaining infrastructure.

It's basically a way to run serverless functions, just like AWS Lambda or Google Cloud Run, but with a few small differences.

**Cost**: At the time of writing this article, it has around **100k free requests per day** (more than enough, even for very famous webpages).

### 🚶‍♀️ A Step-by-Step Guide

This guide assumes you have no/little prior knowledge about Cloudflare and Cloudflare Workers. Though if you're pretty experienced, this guide doesn't compromise on quality over simplicity. 🙃

1. Create your Cloudflare account and add a domain (optional)

![Add a new domain to your Cloudflare account](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mf9r0clpz1fotle10adx.png) 

Follow the usual instructions on configuring the domain's nameservers, as illustrated in their ['adding a site' docs](https://developers.cloudflare.com/fundamentals/get-started/setup/add-site/)!

If you aren't managing your DNS through Cloudflare, point the domain to Cloudflare's servers. Read their docs for more info.

2. Add your Cloudflare worker Route

![Cloudflare Worker add route](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g1a5ongkcl2nzer8xcoo.png)

3. Add the catch-all domain/sub-domain

![Add the domain](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cchwrcekwmy30r0o2xse.png)

4. Click "Manage Workers", and create a new worker Service.

![Create a new Worker Service](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rbeip3u5loanhjxtxr9b.png)

5. Select the second option (HTTP Router) when creating the worker, since we don't just want to send a simple response

![Select HTTP Router 2nd option](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p3w5svx6ms3oy21z4pfr.png)

6. Open the web code-editor to quickly edit the Cloudflare Worker logic

![Open the code-editor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z8w9mn22bz203ciixntz.png)

7. Edit/Paste the code, and preview

![Edit the domain and Preview!](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bmea6bu6yazrxexjezi4.png)

Edit the default code snippet that's already in the editor, or add the following:

```js
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)  {
  return fetch("https://justmohit.bio.link");
}
```

9. Assign the custom domain to your worker

![Assign the custom domain](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0yda5vcr4yiaeaj3lkmz.png)

And that's it!

### 🎉 Reap the Benefits: Analytics, Caching & Custom Domains

We can now access the contents of [justmohit.bio.link](https://justmohit.bio.link) at [links.mohitya.dev](https://links.mohitya.dev). Heck, we even get simple analytics, without the option being enabled by the bio.link team!

![Domain changed image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lfopv15jn86jd7qg5dl5.png)

Also, get instant feedback on anything the server sends, including status codes, requests, etc. and the data is persisted for weeks at end in the free tier!

![Screenshot of analytics](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e6pufl59o5an3a1hm596.png)

### 😱 Taking it to the next level: Edit response HTML

We could change the Cloudflare Workers code in order to change the response that is displayed to the end user!

For example, we could use it to our advantage (for educational purposes only, of course) by removing a watermark on a website that requires a premium subscription to remove it.

You could find more info on how to modify response content using Cloudflare Workers on their [HTML Rewriter docs](https://developers.cloudflare.com/workers/runtime-apis/html-rewriter/)

### 🙈 A few Alternatives

Though I'm not fond of paying for a webpage with such a low view count, I'd still like to highlight some alternatives:

**Paid**: _[Ably.host](https://ablyhost.com/?utm_campaign=mohits-blog&utm_source=devto-workers-blog)_ - Host any website on your subdomain within a few minutes (no-code alternative)

![Ably Host](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yzxx8f6fjvh1fc9vj9ng.png)

**Free**: _Self-hosted Nginx_ - (If you want to manage everything)

![Nginx logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dtweohl2qd2ztbah0ue2.png)

Nginx could be easily used as a reverse proxy, for routing both internal, and external traffic! [Learn more](https://phoenixnap.com/kb/nginx-reverse-proxy)

### 👋 That's it!

Thanks for reading along! Let me know how/what you're using this for, if you've tried to follow along! Till then, see you later...

![Bye Bye](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3xf76tsrt2ng234mzj0q.gif)