|
| 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 | +}; |
0 commit comments