Created
April 27, 2024 17:22
-
-
Save xettri/937ad920bd3d0b9159744ae9c2e71dc2 to your computer and use it in GitHub Desktop.
Simple nodejs http proxy, works with https and http forwarding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require("http"); | |
const https = require("https"); | |
// Ignore SSL error | |
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; | |
const createProxyServer = ({ url, headers, responseHeaders } = {}) => { | |
let forwardUrl; | |
try { | |
forwardUrl = new URL(url); | |
console.log("Setting up proxy for:", url); | |
} catch (e) { | |
console.log("Invalid url:", url); | |
throw e; | |
} | |
return http.createServer((req, res) => { | |
const requestUrl = new URL(req.url, `http://${req.headers.host}`); | |
const options = { | |
hostname: forwardUrl.hostname, | |
port: forwardUrl.protocol === "https:" ? 443 : 80, | |
path: requestUrl.pathname + requestUrl.search, | |
method: req.method, | |
headers: { | |
...req.headers, | |
...headers, | |
}, | |
}; | |
const proxyServer = options.port === 443 ? https : http; | |
const proxyReq = proxyServer.request(options, (proxyRes) => { | |
const proxyResHeaders = { ...proxyRes.headers }; | |
if (responseHeaders["access-control-allow-origin"]) { | |
delete proxyResHeaders["access-control-allow-origin"]; | |
// if not set then Origin can add this and duplicate value will be | |
// served as we overwrite below | |
res.setHeader( | |
"Access-Control-Allow-Origin", | |
responseHeaders["access-control-allow-origin"] | |
); | |
} | |
const proxyResponseHeaders = { | |
...proxyRes.headers, | |
...responseHeaders, | |
}; | |
res.writeHead(proxyRes.statusCode, proxyResponseHeaders); | |
proxyRes.pipe(res, { end: true }); | |
}); | |
proxyReq.on("error", (err) => { | |
console.error("Proxy Request Error:", err); | |
res.statusCode = 500; | |
res.end("Proxy Request Error"); | |
}); | |
// Forwarding request body if exists | |
if (req.method !== "GET" && req.method !== "HEAD") { | |
req.pipe(proxyReq, { end: true }); | |
} else { | |
proxyReq.end(); | |
} | |
}); | |
}; | |
const server = createProxyServer({ | |
url: "https://api.example.com", | |
// custom header if you want to pass | |
headers: { | |
Origin: "http://localhost:3000", | |
}, | |
// custom response header if you want in return | |
responseHeaders: {}, | |
}); | |
const PORT = process.env.PROXY_PORT || 4444; | |
server.listen(PORT, () => { | |
console.log(`Proxy server is running on port ${PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment