Node.js: Using Connect with Express

Connect is a middleware framework for Nodejs and is used in several projects like Express. Today I’ll show you a simple example of how to use some of the Connect bundled middleware in an Express application.

Assuming you have Nodejs installed and are ready to go, make sure to use npm to install the latest Express. I’ll install mine locally to the folder I’m currently working in like this:

$ npm install express

Lets use the Connect logger and responseTime middleware. The logger gives a configurable output and the responseTime will tell you how long a response took by placing a value in the headers (X-Response-Time).

Update Sept 14, 2012: With Express 3 keep in mind that createServer has been deprecated. You can modify the above code like below to get rid of the deprecation warning:

app = express();
app.use(express.bodyParser())

You can see how easy it is to add Connect middleware. Using Express you simply add the middleware you want, in this case I added it in via createServer.

Now go to the URL (you might want to use a browser add-on to see the headers more easily, for Chrome try the XHR Poster). In the header you should see something similar to this:

X-Response-Time 0ms

Obviously our server is so fast at this point since it only serves up the text “Hello World” that it took essentially no time to process and response. However if you were actually doing some something more you will see the value go up. Just as an example you could temporarily block the server with a timer if you wanted to see the value change.