Skip to content

Instantly share code, notes, and snippets.

@shisama
Last active September 20, 2023 14:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shisama/0406fbc1a54d69350d6d17a31fc3d1e2 to your computer and use it in GitHub Desktop.
Save shisama/0406fbc1a54d69350d6d17a31fc3d1e2 to your computer and use it in GitHub Desktop.
Node.js Proxy Server with Basic Auth Sample
const http = require("http");
const { parse } = require("basic-auth");
const { PROXY_USERNAME, PROXY_PASSWORD } = process.env;
const PROXY_PORT = process.env.PROXY_PORT || 8000;
const check = (credentials) => {
return (
credentials &&
credentials.username === PROXY_USERNAME &&
credentials.pass === PROXY_PASSWORD
);
};
const proxy_server = http.createServer(function (request, response) {
const credentials = parse(request.headers["proxy-authorization"]);
if (!check(credentials)) {
response.statusCode = 401;
response.end("Access denied");
}
const options = {
port: 80,
host: request.headers["host"],
method: request.method,
path: request.url,
headers: request.headers,
};
const proxy_request = http.request(options);
proxy_request.on("response", function (proxy_response) {
proxy_response.on("data", function (chunk) {
response.write(chunk, "binary");
});
proxy_response.on("end", function () {
response.end();
});
response.writeHead(proxy_response.statusCode, proxy_response.headers);
});
request.on("data", function (chunk) {
proxy_request.write(chunk, "binary");
});
request.on("end", function () {
proxy_request.end();
});
});
proxy_server.listen(PROXY_PORT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment