3

I'm using Grunt and its proxying library grunt-connect-proxy. I have two servers setup for the desktop and mobile versions of my site (both of which have separate assets and such, hence the separation). Both sites are hosted on 0.0.0.0 but on different ports (9000 and 10000).

How can I proxy requests to the two different servers based on the User-Agent header (which will tell me if it is a mobile or desktop user)? Is there another solution in NodeJS I could use?

liamzebedee
  • 14,010
  • 21
  • 72
  • 118

1 Answers1

1

I ended up writing a NodeJS server which used the http-proxy and mobile-detect packages to proxy requests.

var servers = {
  desktopClientFrontend: 'http://0.0.0.0:10000',
  mobileClientFrontend: 'http://0.0.0.0:9000',
  railsApiBackend: 'http://0.0.0.0:11000'
};

var http = require('http'),
    url = require('url'),
    httpProxy = require('http-proxy'),
    MobileDetect = require('mobile-detect');

var proxy = httpProxy.createProxyServer({});

proxy.on('error', function (err, req, res) {
  res.writeHead(500, {
    'Content-Type': 'text/plain'
  });

  res.end('Something went wrong. And we are reporting a custom error message.');
});

var server = http.createServer(function(req, res) {
  if(url.parse(req.url).pathname.match(/^\/api\//)) {
    proxy.web(req, res, { target: servers.railsApiBackend });
  } else {
    var mobileDetect = new MobileDetect(req.headers['user-agent']);
    if(mobileDetect.mobile()) {
      proxy.web(req, res, { target: servers.mobileClientFrontend });
    } else {
      proxy.web(req, res, { target: servers.desktopClientFrontend });
    }
  }
});

server.listen(80);
liamzebedee
  • 14,010
  • 21
  • 72
  • 118