Skip to content

Instantly share code, notes, and snippets.

@morgan9e
Created January 2, 2024 15:12
Show Gist options
  • Save morgan9e/e727342bef8042f07e96c1022c3034ed to your computer and use it in GitHub Desktop.
Save morgan9e/e727342bef8042f07e96c1022c3034ed to your computer and use it in GitHub Desktop.
cfproxy.js
async function handleRequest(request) {
const originalHeaders = request.headers;
const proxyUrl = originalHeaders.get('X-Proxy-URL');
const proxyMethod = originalHeaders.get('X-Proxy-Method') || 'GET';
const proxyHeaders = originalHeaders.get('X-Proxy-Headers') || null;
let parsedProxyHeaders = {};
if (proxyHeaders) {
try {
parsedProxyHeaders = JSON.parse(proxyHeaders);
} catch (err) {
return new Response('X-Proxy-Headers must be valid JSON', { status: 400 });
}
}
const proxiedRequest = new Request(proxyUrl, {
method: proxyMethod,
headers: parsedProxyHeaders,
});
try {
const response = await fetch(proxiedRequest);
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
} catch (error) {
return new Response('Error fetching proxied URL', { status: 500 });
}
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment