Book Advanced Express Web Application Development

Book cover

I had opportunity to ┬áread a book “Advanced Express Web Application Development”. There are many books written about using Express.js framework, some of are good and some not so good. This book gives you good ground understanding of the Node.js Express usage and example of how to develop solid application. Through the book you are working on single-page application called “Vision“, which covers both the client side (Backbone) and server-side development.

Some of the key points and topics what I liked in this book:

  • Single application through book, not just random code snippets which does not give the understanding how the project structure should be
  • Test driven development – TDD all the server-side code is tested
  • Scaling: vertical and horizontal – many books miss this chapter but that’s the reason you are using Node.js, right ? Actually this is large topic and needs to be covered more, maybe in future “someone” writes a book about scaling in Node.js.
  • Lastly there is the chapter of making your application ready for production

Well if you are using Express daily ┬áthis is “must read” book because there are many useful tips an guides you might find and apply in your projects.


Creating simple blog with Node.js: flash messages

One way to give user feedback is to use the flash messages, after certain action you display information. Example user deletes the post and is redirected to main page, now display the information if all were successful or not.

To make use of the flash messages you need to add the cookieParser

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

This is the way to add information to flash messages, you can acces the object by req.flash().

if (!err) {
  req.flash('info', 'Post has been sucessfully edited');

To use it in all the view so I would not have to pass the flash object into every render function, is to register helper.

  flash: function(req, res) {
    return req.flash();

Also i have added into layout.jade before header partial !=partial(‘alert’, flash) and in view partial is the message look.

mixin showAlert(alerts)
    for alert in alerts
      div #{alert}

- if (
    mixin showAlert(

- if (flash.success)
    mixin showAlert(flash.success)

- if (flash.error)
    mixin showAlert(flash.error)

Creating simple blog with Node.js (express and mongodb)

Libraries toolkits used in this project:

  • jade
  • express
  • mongojs
  • twitter-bootstrap
  • momentjs

Let’s start creating new blog project by creating the empty express project.

express blog

The output should look like this:

create : blog
create : blog/package.json
create : blog/app.js
create : blog/public
create : blog/routes
create : blog/routes/index.js
create : blog/views
create : blog/views/layout.jade
create : blog/views/index.jade
create : blog/public/stylesheets
create : blog/public/stylesheets/style.css
create : blog/public/javascripts
create : blog/public/images

dont forget to install dependencies:
$ cd blog && npm install

Requirements for our simple blog(must contain the CRUD):

  • Add new blog posts (Create).
  • View the list of all our posts, order by latest create date (Read, there should be separate “full text” read).
  • All make mistakes, we need to make the post editable by author, it would be good to use create form (Update).
  • Remove the posts, maybe not delete but also change state to unpublished, but also provide the delete (Delete).
  • Commenting in separate post view.
  • Login for blog owner and for publishers.
The design and web structure will be created with the twitter bootstrap library, simple way to create good looking site with small amount of time.

Lets create basic structure of our mongo data model.

var post = {
subject: 'This the test subject'
, body: 'Body should contain the markdown content'
, tags: [ 'first', 'mongodb', 'express']
, created: new Date()
, modified: new Date()
, state: 'published'
, author: {
username: 'estveeb'
, comments: [
name: 'Test user'
, body: 'I like your blog'
, created: new Date()

Next thing is to add the simple wrapper library to communicate mongodb, called Mongojs. To start the connection to database add this to app.js and then add the posts query to your router. Run the node app.js and open browser type localhost:3000.

db = require('mongojs').connect('blog', ['post']);
app.get('/', function(req, res) {
  var fields = { subject: 1, body: 1, tags: 1, created: 1, author: 1 };{ state: 'published'}, fields, function(err, posts) {
    if (!err && posts) {
      res.render('index.jade', { title: 'Blog list', postList: posts });

Showing individual blog post, we will be using route param pre condition which will be accessed before going through route itself. In our case we are making the request to database to make sure the post exists.

// Route param pre condition
app.param('postid', function(req, res, next, id) {
  if (id.length != 24) return next(new Error('The post id is not having correct length'));{ _id: db.ObjectId(id) }, function(err, post) {
    if (err) return next(new Error('Make sure you provided correct post id'));
    if (!post) return next(new Error('Post loading failed')); = post;

app.get('/post/:postid', function(req, res) {
  res.render('show.jade', {
    title: 'Showing post - ' +,

In the blog post view we need to add the fields for commenting(name, comment) and handle the post request if some of the comments is posted. For security reason there is need to check if the blog post is in the post’s collections or not, in my code i haven’t added.

// Add comment'/post/comment', function(req, res) {
  var data = {
    , body: req.body.comment
    , created: new Date()
  };{ _id: db.ObjectId( }, {
    $push: { comments: data }}, { safe: true }, function(err, field) {

The functionality without authentication is covered now we need to add the auth also, for adding new posts, editing and deleting. We will implement really basic auth system the user has username, password which are sent to server compare the hashes and give user access or not. I don’t like examples which use plain password fields so we use sha256 + salt to generate hashes.
The routes which need to have authenticated user, has middleware check for access rules.

// Login
app.get('/login', function(req, res) {
  res.render('login.jade', {
    title: 'Login user'

app.get('/logout', isUser, function(req, res) {
});'/login', function(req, res) {
  var select = {
      user: req.body.username
    , pass: crypto.createHash('sha256').update(req.body.password + conf.salt).digest('hex')

  db.user.findOne(select, function(err, user) {
    if (!err && user) {
      // Found user register session
      req.session.user = user;
    } else {
      // User not found lets go through login again


Now the adding post functionality, which checks the user state logged in or not and then inserts data.

app.get('/post/add', isUser, function(req, res) {
  res.render('add.jade', { title: 'Add new blog post '});
});'/post/add', isUser, function(req, res) {
  var values = {
      subject: req.body.subject
    , body: req.body.body
    , tags: req.body.tags.split(',')
    , state: 'published'
    , created: new Date()
    , modified: new Date()
    , comments: []
    , author: {
        username: req.session.user.user
  };, function(err, post) {
    console.log(err, post);

In the last version I added simple editing and deleting also. In edit we do the check if article exists and then render the editor, also we can fake the POST values so there is need for additional database query before starting $set.

app.get('/post/edit/:postid', isUser, function(req, res) {
res.render('edit.jade', { title: 'Edit post', blogPost: } );
});'/post/edit/:postid', isUser, function(req, res) {{ _id: db.ObjectId( }, {
$set: {
subject: req.body.subject
, body: req.body.body
, tags: req.body.tags.split(',')
, modified: new Date()
}}, function(err, post) {

Delete functionality has to be redone as it is not good idea to delete the posts with GET which parameters come from url, also no additional check if the user clicked it by accident, so there must be also some confirm buttons.

app.get('/post/delete/:postid', isUser, function(req, res) {{ _id: db.ObjectId(req.params.postid) }, function(err, field) {

I have left out many features, because the post would have gone to long, there is no editing or deleting feature, also validating data and filtering. I will add the features later with some updates to my code, any major feature is going to be covered in my blog. Check out my github page for newer implementations.