Follow @endyourif rss Facebook LinkedIn

Setup routes in Node.js with Express.js and Jade with controllers, models, and views Setup routes in Node.js with Express.js and Jade with controllers, models, and views

Published on Jul 14, 2019

I like the structure of Model View Controller (MVC) and I wanted to apply it to my Node.js projects.

I've written previous articles about Node using Jade Templates with Express, but I didn't go into much details about code organization; let's do that now.

MVC implementation with Node.js

Structure wise, here is my preference:

  • /

    • config

    • controllers

    • models

    • public

      • css

    • views

      • controllerName

        • index.jade

  • app.js

  • routes.js

In the above structure, I create one file per controller, model, and a sub folder in the views directory to hold my Jade templates.

App.js and Route.js Setup

Example app.js setup

var express = require('express');

var app = module.exports = express.createServer();

var config = require('./config/config');

// Configuration, defaults to jade as the view engine
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));

app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));

app.listen(80, function(){
console.log("Express server listening on port 80");
}); = app;
routes = require('./routes');

The above code sets up Express and Jade as the templating engine, initializes the web server and loads the routes.js file.

Example routes.js setup

app =;

/* require your controllers here */
var homeController = require('./controllers/home');
var userController = require('./controllers/user');

app.get('/', homeController.index);

app.get('/users', userController.index);
app.get('/users/detail', userController.detail);

This instantiates two controllers: home and user. Then one route is created for / that calls the index function in the home controller and two routes are created for the user controller: index and detail.

Hopefully this is a good structure to get you started with using MVC, Express.js, and Jade templates.

Tags: Node js Tutorial | express | jade

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP