HAPI a good Express alternative

HAPI a good Express alternative

Express JS is the leading application framework in the MEAN stack universe. Also the E of the stack name is referred to it, but if you are curious about valid alternatives one to consider is Hapi JS.

Hapi is a NodeJS application framework relatively young but trusted by some major company like Paypal, Disney and a lot more. The project is also very active on github with about 4200 commit and 126 contributors. The actual release is the 8.4.

A basic Hapi server

Starting from the tutorial where we created the basic MEAN stack and changing the server.js file you can modify the stack to run with Hapi. First of all we need to get the Hapi JS from npm.

npm install --save hapi

Differently from Express the Hapi framework use a proprietary HTTP server implementation that can be started with some line of code. Modify the server.js as follow :


var Hapi        = require('hapi');
var Path 	= require('path');

// set our port
var port = 3000; 

var server = new Hapi.Server();
server.connection({ port: 3000 });

server.views({
    engines: {
        html: require('handlebars')
    },
    path: Path.join(__dirname, 'public')
});


server.start(function () {
    console.log('Server running at:', server.info.uri);
});

server.route([

	{
	    method: 'GET',
	    path: '/',
	    handler: function (request, reply) {
	        reply.view('index');
	    }
	},
	{
	    method: 'GET',
	    path: '/{param*}',
	    handler: {
	        directory: {
	            path: 'public',
	            listing: true
	        }
	    }
	}
]);


The Hapi server can use almost every template engine but the standard is handlebar that you can get via bower.

bower install handlebar --save

Now if you start the server with

node server.js

all the objects in the public folder will be served as a normal http server. If you want to use AngularJS there is a little modification to make to the app.js file. The Handlebar template engine use the same bracket symbol of AngularJS so we have to change it. Nothing more easy, just two line of code in the app.js file :


var app = angular.module('myApp', []);

app.config(function($interpolateProvider) {
  $interpolateProvider.startSymbol('{[{');
  $interpolateProvider.endSymbol('}]}');
});


From now on AngularJS scope context will be initialized with {[{ }]}

This is not a complete tutorial but just a introduction to a valid alternative to the standard MEAN stack. We are working about benchmarking the Hapi framework and will post the result as soon at will be completed.

Adam Brown
Please follow and like us:

Leave a Comment