Skip to content

Instantly share code, notes, and snippets.

@mike-luabase
Forked from timgl/cloudflare-worker.js
Created July 21, 2022 20:39
Show Gist options
  • Save mike-luabase/ab8a8c01e711c27e979c49955e924333 to your computer and use it in GitHub Desktop.
Save mike-luabase/ab8a8c01e711c27e979c49955e924333 to your computer and use it in GitHub Desktop.
const API_URL = 'https://app.posthog.com/';
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,HEAD,POST,OPTIONS',
'Access-Control-Max-Age': '86400',
};
const ORIGIN = new URL(API_URL).origin
async function handleRequest(request) {
const url = new URL(request.url);
url.host = 'app.posthog.com'
ph_request = new Request(url, request);
ph_request.headers.set('Origin', ORIGIN);
let response = await fetch(ph_request);
response = new Response(response.body, response);
response.headers.set('Access-Control-Allow-Origin', new URL(request.headers.get('referer')).origin || '*');
response.headers.append('Vary', 'Origin');
return response;
}
function handleOptions(request) {
let headers = request.headers;
if (
headers.get('Origin') !== null &&
headers.get('Access-Control-Request-Method') !== null &&
headers.get('Access-Control-Request-Headers') !== null
) {
// Handle CORS pre-flight request.
let respHeaders = {
...corsHeaders,
'Access-Control-Allow-Headers': request.headers.get('Access-Control-Request-Headers'),
};
return new Response(null, {
headers: respHeaders,
});
} else {
return new Response(null, {
headers: {
Allow: 'GET, HEAD, POST, OPTIONS',
},
});
}
}
addEventListener('fetch', event => {
const request = event.request;
const url = new URL(request.url);
if (request.method === 'OPTIONS') {
event.respondWith(handleOptions(request));
} else if (request.method === 'GET' || request.method === 'HEAD' || request.method === 'POST') {
event.respondWith(handleRequest(request));
} else {
event.respondWith(
new Response(null, {
status: 405,
statusText: 'Method Not Allowed',
})
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment