-
Notifications
You must be signed in to change notification settings - Fork 14
/
esbuild.proxy.mjs
45 lines (40 loc) · 1.17 KB
/
esbuild.proxy.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import http from 'node:http';
/**
* Create proxy server that will forward requests to esbuild local server.
* @see https://esbuild.github.io/api/#serve-proxy
*/
export function createProxyServer(localServer, proxyPort = 3001) {
const listenerFn = requestListener(localServer);
http.createServer(listenerFn).listen(proxyPort);
console.log(
'\x1b[1m\x1b[92m',
'> Open this 🦙 \x1b[4mhttp://' +
localServer.host +
':' +
proxyPort +
'/\x1b[0m\n'
);
}
function requestListener({ host, port }) {
return function (req, res) {
const forwardRequest = (path) => {
const options = {
hostname: host,
port: port,
path,
method: req.method,
headers: req.headers,
};
const proxyReq = http.request(options, (proxyRes) => {
// If esbuild local server return 404, use SPA router config for fallback
if (proxyRes.statusCode === 404) {
return forwardRequest('/');
}
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});
req.pipe(proxyReq, { end: true });
};
forwardRequest(req.url);
};
}