Reverse proxy is a proxy server which retrieve resources on behalf of client from one or more servers. Client end need not to know about all those servers. They request to proxy server on specific URL with over HTTP and proxy server finds out where to look ( in Servers ) to serve that request.
In this tutorial we will learn and develop proxy server using Express.js. Our proxy server will :
- Contain 3 different server running on different port.
- Accept requests and return response.
About http-proxy :
Http-proxy is a node module developed by Nodejitsu, one of the leading Node.js hosting provider. This module will help us to write Reverse proxy in Node.js very easily.
Project installation :
Create new Node.js project and create package.json file. It is recommended to use npm init command to generate one.
Once done use following command to install Express.js and http-proxy.
Server code
In order to run our reverse proxy server we need some resource server from which Proxy will fetch data. In order to do so, let’s develop three Express server running on Port 3001,3002,3003 respectively.
var app = express();
app.get(‘/app1’,function(req,res) {
res.send(“Hello world From Server 1”);
});
Copy paste same code for other servers too and change the text.
Proxy Server Code
Here is our simple proxy server code in express.js with multiple targets.
var app = express();
var httpProxy = require('http-proxy');
var apiProxy = httpProxy.createProxyServer();
var serverOne = 'http://localhost:3001',
ServerTwo = 'http://localhost:3002',
ServerThree = 'http://localhost:3002';
app.all(“/app1/*”, function(req, res) {
console.log(‘redirecting to Server1’);
apiProxy.web(req, res, {target: serverOne});
});
app.all(“/app2/*”, function(req, res) {
console.log(‘redirecting to Server2’);
apiProxy.web(req, res, {target: ServerTwo});
});
app.all(“/app3/*”, function(req, res) {
console.log(‘redirecting to Server3’);
apiProxy.web(req, res, {target: ServerThree});
});
You can add as many targets you want and it will create a proxy for that. In order to check whether its working or not we need to first run all the servers and hit request to /app1 and /app2 etc.
Running the app
Put all server in running mode, including proxy one. Note the servers are as follows :
==> localhost:3000 – Reverse proxy server.
== >localhost:3001 – First resource server.
…
You can hit the other server target URL too and it will return a response from second server.
Conclusion :
Reverse proxy is one of the famous approach when it comes to security. Real world user will never know from which server resource came from. Developing reverse proxy from core in Node.js is little tricky but thanks to awesome contribution as http-proxy, our life is easier.