Tuesday, February 20, 2018

Node.js Reverse Proxy


Summary

In this post I'll show how to create a simple reverse proxy server in Node.js.

Environmentals

The scenario here is front-ending an app server (in this case Genesys Mobility Services (GMS) with a proxy to only forward application-specific REST API requests to GMS over HTTPS.  The proxy also acts as a general web server as well - also over HTTPS.

Code

  1. var path = require('path');
  2. var fs = require('fs');
  3. var gms = 'https://svr2:3443';
  4.  
  5. var express = require('express');
  6. var app = express();
  7. var privateKey = fs.readFileSync('./key.pem');
  8. var certificate = fs.readFileSync('./cert.pem');
  9. var credentials = {key: privateKey, cert: certificate};
  10. var https = require('https');
  11. var httpsServer = https.createServer(credentials, app);
  12.  
  13. var httpProxy = require('http-proxy');
  14. var proxy = httpProxy.createProxyServer({
  15. secure : false,
  16. target : gms
  17. });
  18.  
  19. httpsServer.on('upgrade', function (req, socket, head) {
  20. proxy.ws(req, socket, head);
  21. });
  22.  
  23. proxy.on('error', function (err, req, res) {
  24. console.log(err);
  25. try {
  26. res.writeHead(500, {
  27. 'Content-Type': 'text/plain'
  28. });
  29. res.end('Error: ' + err.message);
  30. } catch(err) {
  31. console.log(err);
  32. }
  33. });
  34.  
  35. app.use(express.static(path.join(__dirname, 'public')));
  36.  
  37. app.all("/genesys/*", function(req, res) {
  38. proxy.web(req, res);
  39. });
  40.  
  41. httpsServer.listen(8443);
Lines 1-11:  Set up a HTTPS server with Express.  The proxy target is specified in Line 3.
Lines 13-17:  Set up the Proxy.  I'm using a self-signed certificate on Svr 2, so 'secure' is set to false to support that.
Lines 19-21:  Configure the HTTPS server use the Proxy to proxy websockets.
Line 35:  Serve up static content (HTML, CSS, Javascript) from the 'public' directory for general requests to this server.
Lines 37-39:  Proxy any requests that are specifically to the GMS REST API, both HTTPS and WSS traffic.

Source:  https://github.com/joeywhelan/Revproxy/

Copyright ©1993-2024 Joey E Whelan, All rights reserved.