Skip to content

Commit 33edd24

Browse files
committed
feat: implement PostHog proxy worker with CORS support and routing
1 parent 13c9807 commit 33edd24

3 files changed

Lines changed: 42 additions & 1 deletion

File tree

site/docusaurus.config.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,8 @@ const config: Config = {
5555
'posthog-docusaurus',
5656
{
5757
apiKey: process.env.POSTHOG_API_KEY,
58-
appUrl: process.env.POSTHOG_HOST,
58+
appUrl: 'https://raidcli.dev/ingest',
59+
ui_host: process.env.POSTHOG_HOST,
5960
enableInDevelopment: false,
6061
},
6162
]]

workers/posthog-proxy/src/index.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
const POSTHOG_ASSETS_HOST = 'https://us-assets.i.posthog.com';
2+
const POSTHOG_API_HOST = 'https://us.i.posthog.com';
3+
4+
export default {
5+
async fetch(request: Request): Promise<Response> {
6+
const url = new URL(request.url);
7+
8+
// Strip the /ingest prefix
9+
const path = url.pathname.replace(/^\/ingest/, '') || '/';
10+
11+
// Route static assets (JS bundle) to the CDN host, everything else to the API host
12+
const origin = path.startsWith('/static/') ? POSTHOG_ASSETS_HOST : POSTHOG_API_HOST;
13+
const target = new URL(path + url.search, origin);
14+
15+
const proxied = new Request(target.toString(), {
16+
method: request.method,
17+
headers: request.headers,
18+
body: request.method !== 'GET' && request.method !== 'HEAD' ? request.body : null,
19+
});
20+
21+
const response = await fetch(proxied);
22+
23+
// Pass through with CORS headers so the browser accepts the response
24+
const headers = new Headers(response.headers);
25+
headers.set('Access-Control-Allow-Origin', request.headers.get('Origin') ?? '*');
26+
headers.set('Access-Control-Allow-Credentials', 'true');
27+
28+
return new Response(response.body, {
29+
status: response.status,
30+
headers,
31+
});
32+
},
33+
};
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
name = "posthog-proxy"
2+
main = "src/index.ts"
3+
compatibility_date = "2024-01-01"
4+
5+
routes = [
6+
{ pattern = "raidcli.dev/ingest/*", zone_name = "raidcli.dev" },
7+
]

0 commit comments

Comments
 (0)