|
| 1 | +type WorkerEnv = { |
| 2 | + UPSTREAM_ORIGIN?: string; |
| 3 | +}; |
| 4 | + |
| 5 | +function jsonResponse(body: unknown, status: number): Response { |
| 6 | + return new Response(JSON.stringify(body, null, 2), { |
| 7 | + status, |
| 8 | + headers: { |
| 9 | + 'content-type': 'application/json; charset=utf-8', |
| 10 | + 'cache-control': 'no-store', |
| 11 | + }, |
| 12 | + }); |
| 13 | +} |
| 14 | + |
| 15 | +export default { |
| 16 | + async fetch(request: Request, env: WorkerEnv): Promise<Response> { |
| 17 | + const configuredOrigin = (env.UPSTREAM_ORIGIN || '').trim(); |
| 18 | + |
| 19 | + if (!configuredOrigin) { |
| 20 | + return jsonResponse( |
| 21 | + { |
| 22 | + error: 'UPSTREAM_ORIGIN is not configured', |
| 23 | + message: |
| 24 | + 'Set UPSTREAM_ORIGIN in your Wrangler env vars to the Node API origin, for example https://api.example.com', |
| 25 | + }, |
| 26 | + 500, |
| 27 | + ); |
| 28 | + } |
| 29 | + |
| 30 | + const incomingUrl = new URL(request.url); |
| 31 | + const upstreamBase = new URL(configuredOrigin.endsWith('/') ? configuredOrigin : `${configuredOrigin}/`); |
| 32 | + const upstreamUrl = new URL(`${incomingUrl.pathname}${incomingUrl.search}`, upstreamBase); |
| 33 | + |
| 34 | + const headers = new Headers(request.headers); |
| 35 | + headers.set('x-forwarded-host', incomingUrl.host); |
| 36 | + headers.delete('host'); |
| 37 | + |
| 38 | + const init: RequestInit = { |
| 39 | + method: request.method, |
| 40 | + headers, |
| 41 | + redirect: 'manual', |
| 42 | + body: request.method === 'GET' || request.method === 'HEAD' ? undefined : request.body, |
| 43 | + }; |
| 44 | + |
| 45 | + return fetch(upstreamUrl.toString(), init); |
| 46 | + }, |
| 47 | +}; |
0 commit comments