How to quickly start a single-page application with Node.js

A problem I experienced while starting coding with NodeJS environment and Express framework is that I had difficulties to quickly make a well structured app. I spent too much time on organizing my modules and writing helpers. Paradoxally with Express, I like the fact that I am free to do what I want and don’t encounter too much constraints due to the framework. At last, it was harder to design front end code than back end code.

To deal with that, I used two tools that fit with my requirements :

CompoundJS : a lightweight framework on top of express. It offers the structure and the vital functions I need to write a good backend and configure express properly.

Edit: If you want to build a small single page-app, have a look atAmericanoa lightweight framework easy to learn (based on ExpressJS).

The bad thing with that choice is that there are no out of the box integration. So, in this article, I will give you a way to make them work together and obtain a well structured single page-app in a minute (see the result here). I won’t cover in this article how code is organized, I can just tell you that it is a typical MVC structure for backend and a Backbone MVC for frontend. Look at their documentations for more.

Create a controller to generate an entry point in app/controllers/application_controller.coffee:

action 'index', ->
render title: "my single page app"

Then create template file for entry point:

mkdir app/views/application
vim app/views/application/index.ejs

fill it with:

<script>require('initialize');</script>

Then add a route to confige/routes.coffee file:

exports.routes = (map) ->
map.get "/", "application#index"

Check that everything is fine by starting server and opening http://localhost:3000/ in your browser (Brunch logo should be displayed):

compound s

4. Use

To make Brunch automatically rebuild you app after each modification, go into the client directory and type:

brunch watch

You can write all your UI code inside client directory. Brunch handles templates too, so don’t worry about writing your html code on client side. Another good thing is that Compound and Brunch offer generators to build your models and controllers faster. Finally, Compound is very efficient for writing REST API : sending and parsing JSON are easy. As you understand, now you have all the stuff you need to build an awesome single-page web application!