Over a million developers have joined DZone.

Node.js: Using Connect with Express

DZone's Guide to

Node.js: Using Connect with Express

· Performance Zone ·
Free Resource

Sensu is an open source monitoring event pipeline. Try it today.

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).

Create a new file called app.js and add the following code:

var express = require('express');
var app = express.createServer(
app.get('/', function(request, response) {
    response.send('Hello World');
console.log('Starting server...')

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.

In the output you will see the logging: - - [Sun, 15 Jan 2012 23:57:13 GMT]
"GET / HTTP/1.1" 200 11 "-"
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2)
AppleWebKit/535.7 (KHTML, like Gecko)
Chrome/16.0.912.75 Safari/535.7"


From http://www.giantflyingsaucer.com/blog/?p=3537

Sensu: workflow automation for monitoring. Learn more—download the whitepaper.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}