Skip to content

Instantly share code, notes, and snippets.

@Kenya-West
Created March 16, 2025 18:10
Show Gist options
  • Save Kenya-West/e96866b4cedaf0c429a6f338d8a25cb9 to your computer and use it in GitHub Desktop.
Save Kenya-West/e96866b4cedaf0c429a6f338d8a25cb9 to your computer and use it in GitHub Desktop.

Cloudflare Workers URL Proxy

This is a simple URL proxy script that forwards requests to a target URL specified by the url query parameter. If no URL is provided or if the URL is invalid, the script returns a 400 error.

Features

  • Proxy Requests: Forwards incoming HTTP requests to a target URL.
  • Error Handling: Returns a 400 error if the URL parameter is missing or invalid.
  • Flexible Request Handling: Supports GET, HEAD, and other HTTP methods.
  • Response Header Customization: Easily adjust response headers (e.g., for CORS).

How It Works

  1. Listening for Requests: The script listens for fetch events.
  2. URL Parsing: It extracts the url query parameter from the incoming request.
  3. Validation: Checks if the provided URL is valid. If not, it returns a 400 error.
  4. Proxying the Request: Creates a new request to the target URL, preserving the original HTTP method, headers, and body.
  5. Returning the Response: Fetches the resource from the target URL and returns the response to the client.

Deployment to Cloudflare Workers

Using Wrangler CLI

Prerequisites

Steps to Deploy

  1. Install Wrangler CLI

    Install the Wrangler CLI globally if you haven't already:

    npm install -g wrangler
  2. Login to Cloudflare

    Authenticate with your Cloudflare account:

    wrangler login
  3. Generate a New Worker Project

    Create a new Worker project (or use an existing one):

    wrangler generate my-worker

    Replace the contents of the generated index.js with the script provided above, or integrate it as needed.

  4. Configure the Project

    Update your wrangler.toml configuration file. For example:

    name = "my-url-proxy"
    type = "javascript"
    account_id = "YOUR_ACCOUNT_ID"
    workers_dev = true
    route = ""
    zone_id = ""

    Replace YOUR_ACCOUNT_ID with your actual Cloudflare account ID. If you're deploying to a specific route, provide the route and zone_id.

  5. Publish Your Worker

    Deploy your Worker by running:

    wrangler publish

    Once published, your Worker will be live at the URL provided by Cloudflare Workers.

Using the Cloudflare Dashboard (GUI)

  1. Log in to Your Cloudflare Account

    Navigate to Cloudflare Dashboard and log in with your credentials.

  2. Access the Workers Section

    From the dashboard, click on Workers & Pages in the sidebar, then select Workers.

  3. Create a New Worker

    Click on the Create a Service (or Create a Worker) button. This will open the online editor with a default script.

  4. Replace the Default Script

    In the online editor, remove the default code and paste in the provided proxy script (next section, scroll down).

  5. Save and Deploy

    Click the Save button and then Deploy (or simply Deploy to Workers) to publish your service. Once deployed, your Worker will be assigned a unique URL, typically in the format https://<service-name>.<random-string>.workers.dev.

Usage

To use the proxy, send an HTTP request with a url query parameter. For example:

https://<your-worker-subdomain>.workers.dev/?url=https%3A%2F%2Fexample.com

The Worker will fetch the resource from https://example.com and return the response.

Contributing

Contributions are welcome! If you have suggestions or improvements, please open an issue or submit a pull request.

License

This project is licensed under the MIT License.

Acknowledgements

Special thanks to OpenAI o3-mini-high model because I would develop this shit times longer. With o3, I completed it in 4 hours even being ill.

addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
// Create a URL object from the incoming request URL.
let incomingUrl = new URL(request.url)
// Retrieve the "url" query parameter.
let targetParam = incomingUrl.searchParams.get('url')
// If no URL parameter is provided, return a 400 error.
if (!targetParam) {
return new Response("Missing URL parameter", { status: 400 })
}
let targetUrl
try {
// Attempt to create a new URL from the provided parameter.
targetUrl = new URL(targetParam)
} catch (e) {
// If the URL is invalid, return a 400 error.
return new Response("Invalid URL", { status: 400 })
}
// Create a new request using the provided target URL.
const modifiedRequest = new Request(targetUrl.toString(), {
method: request.method,
headers: request.headers,
body: request.method === 'GET' || request.method === 'HEAD' ? null : request.body,
redirect: 'follow'
})
// Fetch the resource from the target URL.
let response = await fetch(modifiedRequest)
// Optionally adjust response headers (e.g., for CORS).
let newHeaders = new Headers(response.headers)
// newHeaders.set("Access-Control-Allow-Origin", "*")
// Return the proxied response.
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment