Skip to content

Instantly share code, notes, and snippets.

@morgan9e
Created May 18, 2024 23:12
Show Gist options
  • Save morgan9e/fd26972459d84c441e1d43d05beb99ca to your computer and use it in GitHub Desktop.
Save morgan9e/fd26972459d84c441e1d43d05beb99ca to your computer and use it in GitHub Desktop.
export default {
async fetch(request) {
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET",
"Access-Control-Max-Age": "86400",
"Access-Control-Allow-Headers": "X-Proxy-URL, X-Proxy-Method, X-Proxy-Header",
};
if (request.method === "OPTIONS") {
if (request.headers.get("Origin") &&
request.headers.get("Access-Control-Request-Method") &&
request.headers.get("Access-Control-Request-Headers")) {
return new Response(null, { headers: corsHeaders });
} else {
return new Response(null, { headers: { Allow: "GET" } });
}
}
const url = new URL(request.url)
var pathurl = "";
if (url.pathname == "/" && url.searchParams) {
pathurl = url.search.slice(1);
}
const originalHeaders = request.headers;
const proxyUrl = request.headers.get('X-Proxy-URL') || pathurl;
const proxyMethod = originalHeaders.get('X-Proxy-Method') || 'GET';
const proxyHeaders = originalHeaders.get('X-Proxy-Header') || null;
if (!proxyUrl) {
return new Response(null, {headers: {...corsHeaders}})
}
if (!isValidHttpUrl(proxyUrl)) {
return new Response('Error URL invalid', { status: 500, headers: corsHeaders });
}
let parsedProxyHeaders = new Headers();
if (proxyHeaders) {
try {
const headerObj = JSON.parse(proxyHeaders);
for (const key in headerObj) {
parsedProxyHeaders.append(key, headerObj[key]);
}
} catch (err) {
return new Response('X-Proxy-Headers must be valid JSON', { status: 400 });
}
}
try {
const proxiedRequest = new Request(proxyUrl, {
method: proxyMethod,
headers: parsedProxyHeaders,
});
const response = await fetch(proxiedRequest);
const headers = new Headers(response.headers);
headers.set('Access-Control-Allow-Origin', "*");
headers.set('Cache-Control', "max-age=1800");
headers.set('Vary', "x-proxy-url, x-proxy-method, x-proxy-header");
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: headers,
});
} catch (error) {
console.error('Error fetching proxied URL:', error);
return new Response('Error fetching proxied URL', { status: 500, headers: corsHeaders });
}
},
}
function isValidHttpUrl(string) {
let url;
try {
url = new URL(string);
} catch (_) {
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment