diff --git a/src/utils/proxy.ts b/src/utils/proxy.ts index 4e14b239064..2f141a3a0a8 100644 --- a/src/utils/proxy.ts +++ b/src/utils/proxy.ts @@ -466,16 +466,20 @@ const initializeProxy = async function ({ }) proxy.on('error', (_, req, res) => { - // @ts-expect-error TS(2339) FIXME: Property 'writeHead' does not exist on type 'Socke... Remove this comment to see the full error message - res.writeHead(500, { - 'Content-Type': 'text/plain', - }) + // res can be http.ServerResponse or net.Socket + if ('writeHead' in res) { + res.writeHead(500, { + 'Content-Type': 'text/plain', + }) - const message = isEdgeFunctionsRequest(req) - ? 'There was an error with an Edge Function. Please check the terminal for more details.' - : 'Could not proxy request.' + const message = isEdgeFunctionsRequest(req) + ? 'There was an error with an Edge Function. Please check the terminal for more details.' + : 'Could not proxy request.' - res.end(message) + res.end(message) + } else { + res.end() + } }) proxy.on('proxyReq', (proxyReq, req) => { const requestID = generateRequestID() @@ -661,7 +665,7 @@ const initializeProxy = async function ({ return proxy.web(req, res, options) }, // @ts-expect-error TS(7006) FIXME: Parameter 'req' implicitly has an 'any' type. - ws: (req, socket, head) => proxy.ws(req, socket, head), + ws: (req, socket, head, options) => proxy.ws(req, socket, head, options), } return handlers @@ -876,8 +880,16 @@ export const startProxy = async function ({ const primaryServer = settings.https ? https.createServer({ cert: settings.https.cert, key: settings.https.key }, onRequestWithOptions) : http.createServer(onRequestWithOptions) - const onUpgrade = function onUpgrade(req: http.IncomingMessage, socket: Duplex, head: Buffer) { - proxy.ws(req, socket, head) + const onUpgrade = async function onUpgrade(req: http.IncomingMessage, socket: Duplex, head: Buffer) { + const match = await rewriter(req) + if (match && !match.force404 && isExternal(match)) { + const reqUrl = reqToURL(req, req.url) + const dest = new URL(match.to, `${reqUrl.protocol}//${reqUrl.host}`) + const destURL = stripOrigin(dest) + console.log(`${NETLIFYDEVLOG} WS Redirect ${req.url} to ${destURL}`) + return proxy.ws(req, socket, head, { target: dest.origin, changeOrigin: true, pathRewrite: () => destURL }) + } + return proxy.ws(req, socket, head, {}) } primaryServer.on('upgrade', onUpgrade)