Skip to content

Instantly share code, notes, and snippets.

@thanksshu
Last active May 10, 2024 08:57
Show Gist options
  • Select an option

  • Save thanksshu/7c3f706c0c1155df0e22f6eff8a2efb5 to your computer and use it in GitHub Desktop.

Select an option

Save thanksshu/7c3f706c0c1155df0e22f6eff8a2efb5 to your computer and use it in GitHub Desktop.
CORS proxy in Cloudflare Worker
export default {
/**
* Send request to this API with querys param "url" and "apikey"
* @param {Request} request
* @param {*} env
* @param {*} ctx
* @returns Response
*/
async fetch(request, env, ctx) {
const supportMethods = new Set(['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'PATCH']);
// OPTIONS method must always be supported
supportMethods.add('OPTIONS');
/**
* Handle HEAD, GET, POST, PUT... requests
* @param {Request} request
* @returns Response
*/
const handleRequest = async (request) => {
const url = new URL(request.url);
let targetUrl = url.searchParams.get('url');
if (targetUrl === null) {
return new Response(null, {
status: 400,
statusText: 'Bad Request'
});
}
request = new Request(new URL(targetUrl), request); // Create a mutable request
request.headers.set('Origin', new URL(targetUrl).origin); // Rewrite origin
let response = await fetch(request);
response = new Response(response.body, response); // Create a mutable response
response.headers.set('Access-Control-Allow-Origin', '*');
// Hint the browser to correctly cache the request
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary
response.headers.append('Vary', 'Origin');
return response;
}
/**
* Handle OPTIONS requests
* @param {Request} request
* @returns Response
*/
const handleOptions = async (request) => {
// Check if it's a CORS preflight
if (
request.headers.get('Origin') !== null &&
request.headers.get('Access-Control-Request-Method') !== null &&
request.headers.get('Access-Control-Request-Headers') !== null
) {
// Return the fake response
const headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append("Access-Control-Allow-Credentials", "*");
headers.append('Access-Control-Allow-Methods',
Array.from(supportMethods).join(', '));
headers.append('Access-Control-Allow-Headers', '*');
return new Response(null, {
headers: headers
});
} else {
// A standard OPTIONS request
return handleRequest(request);
}
}
/* Main entry */
const url = new URL(request.url);
if (url.searchParams.get("apikey") == env.APIKEY) {
const method = request.method;
if (method === 'OPTIONS') {
return handleOptions(request);
} else if (supportMethods.has(method)) {
return handleRequest(request);
} else {
return new Response(null, {
status: 405,
statusText: 'Method Not Allowed',
});
}
} else {
return new Response(null, {
status: 403,
statusText: 'Unauthorized',
});
}
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment