Easy local development with a node.js proxy

Posted by .

Single page apps & websites-as-APIs are pretty common lately. Due to browsers’ cross-domain security restrictions, designing a front-end on a local machine becomes difficult, unless you deploy the whole app.

We’ve encountered this problem often-enough that I have a ready-made solution: creating a local proxy server that serves my static files as-is, and transparently forwards requests for API calls to the deployed app server. This solution works best when the API and the front-end are to be deployed on the same domain, with all API methods having a URL-prefix — something like /api/*.

You will need:

  • a working node.js installation
  • npm configured and running properly

Create a folder-structure like this:

.
|-- package.json
|-- public
|   `-- index.html
`-- server.js

The public dir will contain your HTMLs, CSS and JS files. The package.json file looks like this:

{
  "name": "your-app-name",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "http-proxy": "0.8.x",
    "connect": "2.3.x"
  }
}

And the server.js file looks like this:

var httpProxy = require('http-proxy'),
    connect   = require('connect'),
    endpoint  = {
      host:   'your-app-domain.com', // or IP address
      port:   80,
      prefix: '/api'
    },
    staticDir = 'public';

var proxy = new httpProxy.RoutingProxy();
var app = connect()
  .use(connect.logger('dev'))
  .use(function(req, res) {
    if (req.url.indexOf(endpoint.prefix) === 0) {
      proxy.proxyRequest(req, res, endpoint);
    }
  })
  .use(connect.static(staticDir))
  .listen(4242);

// http://localhost:4242/api/test will give response
// from http://your-app-domain.com/api/test

To run, just run these commands from your project’s directory:

$ npm install -d
$ node server.js

Now, you can access your HTML/CSS/JS files via http://localhost:4242, and any AJAX calls that the JS needs to make will work with your remote API (as long as you’ve used the right prefix!).

You can download the files from this Gist.

How it works

It’s pretty simple: we’ve made a small node.js webapp that uses the Connect framework and its static middleware in order to serve static assets. The excellent node-http-proxy module by Nodejitsu does the heavy-lifting of proxying the API requests.

Of course, there are other ways, but I prefer this approach since I can can specify multiple API endpoints with minimal fuss, and node-http-proxy can even proxy WebSockets! See the documentation of the module for further details.

Again, you can download the files from this Gist.

Comments are closed.