Reverse proxies are incredibly handy for efficiently managing web traffic, especially when you want to separate your frontend domain from backend services. This article walks through setting up a quick reverse proxy using Cloudflare Workers, with a practical example from WFH Alert.

Why Cloudflare Workers?

Cloudflare Workers let you run serverless JavaScript functions directly at the network edge, offering ultra-low latency and scalability without managing your own infrastructure. Perfect for quickly routing requests without complexity.

Real-World Example

At WFH Alert, we faced limitations with Beehiiv (our email management platform) regarding custom hosting of interactive tools like our Cover Letter Generator. Beehiiv doesn't support custom backend scripts or dynamic tool hosting, so we used Cloudflare Workers to seamlessly proxy our tool hosted elsewhere, maintaining a consistent domain structure for SEO and usability.

Step-by-Step Guide

Step 1: Create a Cloudflare Worker

  1. Log in to your Cloudflare Dashboard.
  2. Navigate to Workers.
  3. Click Create Worker.

Step 2: Configure the Worker Script

Replace the default worker script with the following code:

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

async function handleRequest(request) {
  let url = new URL(request.url);

  // Change the hostname to your backend service
  url.hostname = "your-backend-domain.com"; // Replace with your backend domain
  url.protocol = "https"; // Ensures secure connection

  // Create a new request preserving method and headers
  let newRequest = new Request(url, request);

  // Fetch and return the response from your backend
  return fetch(newRequest);
}

Replace your-backend-domain.com with your backend domain.

Step 3: Deploy and Test Your Worker

  1. Click Save and Deploy.
  2. Test your worker directly in the Cloudflare dashboard or by visiting the provided Workers URL.

Step 4: Configure Route for the Worker

Now you'll want your worker to listen on specific paths:

  • In your Cloudflare Dashboard, go to Workers > Routes.
  • Add a new route, for example:
*.yourdomain.com/tools/example-tool*

Make sure to adjust paths appropriately based on your needs.

Step 5: Verify

Navigate to your configured route, e.g., yourdomain.com/tools/example-tool. You should now see responses directly from your backend server, seamlessly routed via Cloudflare Workers.

Practical Use Cases

  • Decoupling frontend and backend services.
  • Easily integrating external APIs without dealing with CORS.
  • Adding security and caching layers effortlessly.