|
| 1 | +/** |
| 2 | + * Isomorphic fetch that resolves *.localhost subdomains and preserves |
| 3 | + * Host headers across Node.js and browsers. |
| 4 | + * |
| 5 | + * Node.js has two issues with *.localhost subdomains: |
| 6 | + * 1. DNS — fetch('http://auth.localhost:3000/') throws ENOTFOUND |
| 7 | + * because undici doesn't resolve *.localhost to loopback. |
| 8 | + * 2. Host header — Node's fetch treats Host as forbidden and silently |
| 9 | + * drops it, breaking server-side subdomain routing. |
| 10 | + * |
| 11 | + * In browsers *.localhost resolves natively, so createFetch() returns |
| 12 | + * globalThis.fetch as-is. |
| 13 | + */ |
| 14 | + |
| 15 | +export type FetchFunction = typeof globalThis.fetch; |
| 16 | + |
| 17 | +export function isLocalhostSubdomain(hostname: string): boolean { |
| 18 | + return hostname.endsWith('.localhost') && hostname !== 'localhost'; |
| 19 | +} |
| 20 | + |
| 21 | +function buildNodeFetch( |
| 22 | + http: typeof import('node:http'), |
| 23 | + https: typeof import('node:https'), |
| 24 | +): FetchFunction { |
| 25 | + return (input, init) => { |
| 26 | + const url = new URL( |
| 27 | + typeof input === 'string' |
| 28 | + ? input |
| 29 | + : input instanceof URL |
| 30 | + ? input.href |
| 31 | + : input.url, |
| 32 | + ); |
| 33 | + |
| 34 | + if (!isLocalhostSubdomain(url.hostname)) { |
| 35 | + return globalThis.fetch(input, init); |
| 36 | + } |
| 37 | + |
| 38 | + const originalHost = url.host; |
| 39 | + url.hostname = 'localhost'; |
| 40 | + |
| 41 | + return new Promise((resolve, reject) => { |
| 42 | + const headers: Record<string, string> = { |
| 43 | + Host: originalHost, |
| 44 | + }; |
| 45 | + |
| 46 | + if (init?.headers) { |
| 47 | + const entries = |
| 48 | + init.headers instanceof Headers |
| 49 | + ? Array.from(init.headers.entries()) |
| 50 | + : Array.isArray(init.headers) |
| 51 | + ? init.headers |
| 52 | + : Object.entries(init.headers); |
| 53 | + for (const [key, value] of entries) { |
| 54 | + headers[key] = value; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + const protocol = url.protocol === 'https:' ? https : http; |
| 59 | + |
| 60 | + const req = protocol.request( |
| 61 | + url, |
| 62 | + { |
| 63 | + method: init?.method ?? 'GET', |
| 64 | + headers, |
| 65 | + }, |
| 66 | + (res) => { |
| 67 | + const chunks: Buffer[] = []; |
| 68 | + res.on('data', (chunk: Buffer) => chunks.push(chunk)); |
| 69 | + res.on('end', () => { |
| 70 | + const body = Buffer.concat(chunks); |
| 71 | + resolve( |
| 72 | + new Response(body, { |
| 73 | + status: res.statusCode ?? 0, |
| 74 | + statusText: res.statusMessage ?? '', |
| 75 | + headers: res.headers as Record<string, string>, |
| 76 | + }), |
| 77 | + ); |
| 78 | + }); |
| 79 | + }, |
| 80 | + ); |
| 81 | + |
| 82 | + req.on('error', reject); |
| 83 | + |
| 84 | + if (init?.signal) { |
| 85 | + const onAbort = () => { |
| 86 | + req.destroy(new Error('The operation was aborted')); |
| 87 | + }; |
| 88 | + init.signal.addEventListener('abort', onAbort, { once: true }); |
| 89 | + req.on('close', () => { |
| 90 | + init.signal!.removeEventListener('abort', onAbort); |
| 91 | + }); |
| 92 | + } |
| 93 | + |
| 94 | + if (init?.body != null) { |
| 95 | + req.write( |
| 96 | + typeof init.body === 'string' || init.body instanceof Uint8Array |
| 97 | + ? init.body |
| 98 | + : String(init.body), |
| 99 | + ); |
| 100 | + } |
| 101 | + |
| 102 | + req.end(); |
| 103 | + }); |
| 104 | + }; |
| 105 | +} |
| 106 | + |
| 107 | +let _fetch: FetchFunction | undefined; |
| 108 | + |
| 109 | +/** |
| 110 | + * Create an isomorphic fetch function. |
| 111 | + * |
| 112 | + * - In browsers (and Deno/Bun/edge): returns globalThis.fetch as-is. |
| 113 | + * - In Node.js: returns a wrapper that uses node:http/node:https for |
| 114 | + * *.localhost URLs (fixing DNS + Host header) and delegates everything |
| 115 | + * else to globalThis.fetch. |
| 116 | + * |
| 117 | + * The result is cached — calling createFetch() multiple times returns |
| 118 | + * the same function instance. |
| 119 | + */ |
| 120 | +export function createFetch(): FetchFunction { |
| 121 | + if (_fetch) return _fetch; |
| 122 | + |
| 123 | + if (typeof process !== 'undefined' && process.versions?.node) { |
| 124 | + try { |
| 125 | + // eslint-disable-next-line @typescript-eslint/no-require-imports |
| 126 | + const http = require('node:http'); |
| 127 | + // eslint-disable-next-line @typescript-eslint/no-require-imports |
| 128 | + const https = require('node:https'); |
| 129 | + _fetch = buildNodeFetch(http, https); |
| 130 | + return _fetch; |
| 131 | + } catch { |
| 132 | + // node:http unavailable — fall through |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + _fetch = globalThis.fetch; |
| 137 | + return _fetch; |
| 138 | +} |
0 commit comments