Cloudflare Worker
Works for every site whose DNS is proxied by Cloudflare (orange cloud), regardless of what serves the site itself.
Setup
npm create cloudflare@latest x3-proxy -- --type=hello-world --lang=ts
cd x3-proxy
npx wrangler secret put X3_PROXY_KEYexport interface Env {
X3_API_ORIGIN: string;
X3_PROXY_KEY: string;
PROXY_PATH: string;
}
const ALLOWED = /^\/v1\/(?:e|collect|cb|c\/[^/]+|s\/[A-Za-z0-9@._-]+)$/;
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const url = new URL(request.url);
const path = url.pathname.slice(env.PROXY_PATH.length);
if (!url.pathname.startsWith(env.PROXY_PATH) || !ALLOWED.test(path)) return new Response("not found", { status: 404 });
const target = new URL(path + url.search, env.X3_API_ORIGIN);
const isScript = path.startsWith("/v1/s/");
const cache = caches.default;
if (isScript && request.method === "GET") {
const hit = await cache.match(request);
if (hit) return hit;
}
const headers = new Headers();
for (const name of ["user-agent", "origin", "content-type", "accept", "sec-fetch-site", "sec-gpc", "dnt"]) {
const value = request.headers.get(name);
if (value) headers.set(name, value);
}
headers.set("x-3x-client-ip", request.headers.get("cf-connecting-ip") ?? "");
headers.set("x-3x-client-country", request.headers.get("cf-ipcountry") ?? "");
headers.set("x-3x-proxy-key", env.X3_PROXY_KEY);
const upstream = await fetch(target, {
method: request.method,
headers,
body: request.method === "POST" ? await request.arrayBuffer() : undefined,
redirect: "manual",
});
const response = new Response(upstream.body, upstream);
response.headers.delete("set-cookie");
if (isScript && upstream.ok) {
response.headers.set("cache-control", "public, max-age=3600, stale-while-revalidate=86400");
ctx.waitUntil(cache.put(request, response.clone()));
}
return response;
},
};name = "x3-proxy"
main = "src/index.ts"
compatibility_date = "2026-10-01"
routes = [{ pattern = "example.com{{PROXY_PATH}}/*", zone_name = "example.com" }]
[vars]
X3_API_ORIGIN = "{{API_ORIGIN}}"
PROXY_PATH = "{{PROXY_PATH}}"npx wrangler deployReplace example.com with your zone. wrangler secret put stores the proxy key encrypted – it is
never part of the code or wrangler.toml.
Verify
curl -s -o /dev/null -w "%{http_code}\n" https://example.com{{PROXY_PATH}}/v1/s/x3.js200, and on a page using data-host="{{PROXY_PATH}}" the request POST {{PROXY_PATH}}/v1/e
returns 204. Cloudflare removes cf-ipcountry on subrequests to non-Cloudflare origins, which is why
the worker copies it into x-3x-client-country itself.