A *Useful* HTTP Proxy Server in 66 Lines of node.js Code

Here : Proxy.js

See also : DummyServer.js

It runs from the command line and has no dependencies other than node.js (I was tempted to add handling via command.js but that can wait).

Node is a Javascript engine based on V8, the one behind Google Chrome. It’s available for most OSes and is an easy install. It’s in the Ubuntu repository but to be more up-to-date check this ppa.

I got stuck earlier with a bit of work-work where clicking on a browser submit button wasn’t doing what it should have, with Chrome dev tools I couldn’t be sure if it was redirecting or what.  Cue a proxy. I used to use the Java one that was bundled in with Axis2, but as it happens I made one in node.js recently (needed internally for Seki). A few tweaks later and here it is.

The code was originally based on A HTTP Proxy Server in 20 Lines of node.js Code but that uses methods now deprecated.

So, running :

node Proxy.js

and then in a different shell,

$ curl http://localhost:8888/anything

it produces:

Proxy addressing localhost:8080
Serving on localhost:8888
***** Calling localhost:8080/anything *****
Request : {
 "host": "localhost",
 "port": 8080,
 "path": "/anything",
 "method": "GET",
 "headers": {
 "user-agent": "curl/7.32.0",
 "host": "localhost:8888",
 "accept": "*/*"
Response : HTTP 200
 "content-type": "text/plain",
 "date": "Wed, 30 Oct 2013 11:43:49 GMT",
 "connection": "keep-alive",
 "transfer-encoding": "chunked"
Body :
Hello World!

For this example I had:

node DummyServer.js

running in another shell, that produced:

Server running at localhost:8080
 "user-agent": "curl/7.32.0",
 "host": "localhost:8888",
 "accept": "*/*",
 "connection": "keep-alive"
URL = /anything

I’m guessing it’d be fairly straightforward to do the same kind of thing at a lower level using sockets. For more features there’s the npm package node-http-proxy.


Let me know if you think of any little tweaks/additions that might make it more useful.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s