Tag Archives: nodejs

Programming Choices

The past few months have pretty much been both a blur and a grind. Most of my work time has been spent on a classic big, dumb enterprise Java application. They’re a drain to write, and I’ve found it also saps my creativity for trying new things. Java, powerful as it may be, really has become the new COBOL and I definitely don’t want to be one of the grey-beards left maintaining crap code in another decade.

The tough problem is there are too many choices today, and Java ends up being the safe bet by default. There are several other technologies out there that I find more interesting. The challenge is finding the time and project to use them on.

WordPress – Yes, don’t laugh, I said WordPress. We finished up a custom WordPress site for a local home builder and it was a blast. WordPress has grown in to quite the little powerhouse and you can almost think of it as a mini web framework. PHP is a bit kludgy, but no worse than many alternatives. I’d like to get a chance to do another WordPress and push it a bit father.

NodeJS – I really enjoy working with NodeJS. As I’ve mentioned in a prior post, it reminds me of Java in the JDK 1.1 days. NodeJS is fast to work with with, and allows you to build an application about anyway out want due to an emphasis on tightly-focused “micro modules”. Think JavaScript Legos. The downside of NodeJS is it tends to be a lone genius technology. I couldn’t see a large team working on a NodeJS application.

Scala – I’ve never had such a love/hate relationship with a language as a I do with Scala. It feels like a modern language but it is still, at its heart, Java. This can be both a good thing and a bad thing. In some ways, it feels like it tries to be too different from Java, making for an abusive learning curve. And if I wanted to stay on the JVM, I could just keep doing Java and cut through the complex abstraction. Scala has moved to my “watch, but don’t play” list.

There are always other little things that pop up too competing for my attention. Now we’re firmly into spring so I can bust out of the winter doldrums and try to get creative with my coding again. I suspect though I’ll be slitting braincells between WordPress and NodeJS.

CSRF with NodeJS and Express 3

In a recent post I took a look at what it took to configure and use the CSRF protection middleware with Express. The article covered Express v2, and in the intervening few months, we’re already at the doorstep of Express v3, and the new version broke my example.

Express v3 did away with the dynamic helpers, so the code making use of them fails. Fortunately, the CSRF module still works fine; you just need to adjust how you’re using it.

Add the CSRF module to the app configuration in the same way as before. For example, on line 11 below, I add the CSRF middleware to the application. One important caveat is the CSRF module depends on the sessions middleware, so you need to configure session support as seen on line 10, and the CSRF middleware has to come after it in the configuration sequence.

  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.cookieParser('your secret here'));

  app.use(function(req, res, next){
    res.locals.token = req.session._csrf;

  app.use(express.static(path.join(__dirname, 'public')));

Express v3 eliminated dynamic helpers, preferring instead that developers just use middleware. To facilitate setting variables available during template rendering, we can make use of the res.locals property. On line 13 above, we create a middleware handler which puts the CSRF token generated by the CSRF middleware into a variable called token which will be visible to the templates.

Note: this custom middleware to set a value in res.locals has to come before the app.router middleware defined on line 18, and after the app.csrf() middleware on line 12.

Once this is complete, there will be a variable called token available in all templates. This token should then be placed either into a hidden form field or query string parameter called _csrf on any HTTP request other than a GET,HEAD or OPTIONS request. If any other request type is made and this _csrf value is missing, the middleware will reject the request with an 403 - Forbidden status.

Here is an example of using the value in a Jade template for a form. Note on line 2 I create a hidden field for _csrf and set the value to the token property we created in the custom middleware above :

  input(type='hidden', name='_csrf', value=token)
  label(for='color') Color:
  button(type='submit') Save

That’s all that is needed to adjust my previous example to work with Express v3.

NodeJS Tip: Jade with HTML5 Boilerplate

Like every good developer suffering from the Not Invented Here syndrome, I’ve been working on my own version of a NodeJS/Express project template to give me a headstart when goofing around. The HTML5 Boilerplate is a shoe-in, but getting it to play nicely with Jade to produce correctly formatted HTML output was another story.

The problem is all the IE specific conditional comments at the top of the HTML5 Boilerplate. For example:

Jade can handle conditional comments pretty easily within the body of a document, as indicated in the documentation. The problem with using them with the html element is it wants to put a closing html tag inside the comment, which leads to a weird page structure and not closing html tag.

The workaround is a bit ugly, but it got me what I wanted. The following will generate the HTML5 Boilerplate conditional comments with proper HTML using Jade:

!!! 5
//if lt IE 7
//if IE 7
//if IE 8

html(class='no-js', lang='en')
        title= title
        link(rel='stylesheet', href='/stylesheets/bootstrap.css')
        link(rel='stylesheet', href='/stylesheets/font-awesome.css')
        link(rel='stylesheet', href='/stylesheets/style.css')
        script(src='/scripts/require-jquery.js', data-main='scripts/main')
        block content

Yes, ugly is the right word, but fortunately you’ll only need to do this in the layout.

CSRF with NodeJS and Express

(Note: see my updated post for Express v3 compatibility)

I’ve been trying to dig into how to handle the common OWASP web security threats with NodeJS + Express and was hitting my head against the wall on getting the Connect CSRF middleware working correctly with Express. It turned out to be pretty simple once I found all the pieces. For the sake of others, here’s how I got it working.

First, in app.js, configure the middleware. Here’s the block I use:

  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.session({ secret: "changeme" }));
  app.use(express.static(__dirname + '/public'));

Line 9 adds the CSRF middleware, but you also need lines 5 & 6, as the CSRF middleware depends on session support to save the CSRF token on the server.

Once this is configured, you can also add a dynamic handler to simplify inserting the token into your forms. This isn’t strictly required, but it reduces a lot of redundant code if you have multiple forms. The dynamic helper configuration looks like this:

    token: function(req, res) {
        return req.session._csrf;

I’m working with a default Express application, so I’ll add two routes for a form to app.js. The mapping looks like this:

app.get('/form', routes.show);
app.post('/form', routes.save);

And in routes/index.js I added these two handlers:

exports.show = function(req, res) {
    var msg = req.flash('info');
    res.render('form', {title: 'Form Demo', message: msg});

exports.save = function(req,res) {
    req.flash('info','You picked %s', req.body.color);

Finally, to get it all working, create the file views/form.jade with the following content:

p #{message}
    input(type='hidden', name='_csrf', value=token)
    label(for='color') Color:
    button(type='submit') Save

Line 3 is where the magic happens. You need to add a hidden form element with a name of _csrf and the value is derived from calling the dynamic helper we configured above.

Start the application and browse to http://localhost:3000/form and you should see our basic form. If you take a look at the code for the page, you’ll see the form looks like this:

The CSRF token has been inserted in to the form. To test things out, fire up another terminal window and use a cURL request to test it. Run curl -X POST http://localhost:3000/form. The response will be Forbidden. This is due to the CSRF middleware intercepting the POST request and attempting to find the _csrf parameter and compare it to the value the CSRF middleware generated. If the parameter isn’t found, or is invalid, the CSRF middleware will return the HTTP 403 Forbidden status.

The CSRF middleware will look for the CSRF token in three locations. First, it will check for a _csrf property in the request body (req.body._csrf), next it will check fot it on the query string (req.query._csrf), and finally, it will check the request headers (req.headers['x-csrf-token']).

So this takes care of OWASP Risk #5. I’ll take a look at how NodeJS and Express deals with the other OWASP in future posts.

Coding in to 2012

Instead of predictions, last year I made a wish list for Santa of things I wanted to have happen in 2011. Looking back at the list, I guess I must have been pretty naughty last year, because the stocking ended up pretty empty. Here was the list, and what I actually got:

  • Google to kick Oracle’s ass over Android: this turned in to a total stalemate, although I could say Google “won” based on the number of Android activations and the butt-kicking Oracle’s stock is getting. I’m actually pretty ambivalent a year later over who wins. I don’t foresee ever buying a Android device, so the whole battle is orthogonal to my interests.
  • Someone to finally build a good Windows notebook: nothing but a lump of coal for me. Lenovo is probably the closest, but none of the PC makers have hit on a Windows 7 equivalent of the Macbook Pro.
  • ActiveState to push out ActiveRuby: another lump of coal. I’m not too disappointed though. I was expecting Ruby to go more mainstream, but instead it had all the thunder sucked out of it by NodeJS. Ruby is becoming the new Java, without the Java part.
  • Google to buy Sencha (ExtJS): more coal. I’ve actually given up on someone buying Sencha. I’m suspecting they have bigger plans than a simple exit. Unfortunately, the market is getting a lot tougher and they may have missed their sweet spot. Sencha Touch is the best tool going in the mobile JavaScript widget space, but it is only a matter of time before JQuery Mobile, Dojo and KendoUI catch up.
  • World Peace: a whole truckload of coal, along with a story that would take more than a few beers to cover.

In spite of a garage full of coal based on my visions of geek sugarplums for last year, I’ll brave speculating on a few things I would like to see happen this year.

  • Grails will get hot: yes, I bashed the crap out of Grails earlier this year when I let my team give it a try on a project. But since then, Grails 2.0 has gone final, and excellent tooling support has arrived in the form of IntelliJ IDEA 11. I’ve been rocking the world doing some Grails work using Bootstrap and KendoUI, and I really appreciate Grails for providing a bit more structure than Rails without having to jump into the rigid world of Java/Spring. I’ll be doing all my personal projects in Grails this year.
  • Kendo UI sneaks in: I originally wrote off Kendo UI as just an attempt by Telerik to clone ExtJS. It shares the same dual licensing model of ExtJS and plays in the same space. In reality, Kendo UI sits somewhere between JQuery UI and ExtJS. Kendo UI provides a good looking library which is easy to implement since it is based on JQuery. While ExtJS is much richer, it is also much harder to work with — there is no such thing as a casual ExtJS developer. Kendo UI also has excellent theming support, and I expect them to evolve it pretty rapidly throughout the year. Kendo UI is what JQuery UI should have been, and this will the framework to watch.
  • NodeJS jumps the shark: NodeJS busted onto the scene this year and got a lot of people very excited about it. Like a new puppy, it was fast, light and a lot of fun to play with. But now that puppy is taking on weight and the peeing on the carpet is starting to get old. Things will only get worse now that NodeJS has sold their souls to Microsoft. I expect NodeJS to enjoy a record short 15 minutes of fame, at the expense of Ruby on Rails.
  • Evil is the new Black: everyone should realize by now that every large technology company is evil. From Facebook and Google stealing your lives to pitch you advertising, to Apple and their walled garden, all these major companies are running with their own evil agendas and we’re just along for the ride. Even Twitter is jumping on the Evil bandwagon. 2012 will be the year you learn to get over it, and there will be good money to be made riding on Darth Vader’s cloak tails. Evil will be the new black.