Created
January 2, 2024 15:12
-
-
Save morgan9e/e727342bef8042f07e96c1022c3034ed to your computer and use it in GitHub Desktop.
cfproxy.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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