Minimum JS Required to Get Express Handlebars Running for Node.js
Posted on August 6, 2016 in Node.js by Matt Jennings


  1. Install the following modules, using the commands below and pressing Enter after each one:
    npm install express --save
    npm install express-handlebars --save
    npm install nodemon --save
  2. Create a server.js file inside your root directory and insert the code listed below:
    // Module that deals with routing and
    // "require" loads an additional library
    var express = require('express');
    // Express handlebars module
    var exphbs = require('express-handlebars');
    // An instance of the express app
    var app = express();
    // Tell express to use handlebars as it's templating engine
    // and look for a file called "views/layouts/base.handlebars" for
    // the master layouts and then other files inside "views"
    app.engine('handlebars', exphbs({defaultLayout: 'base'}));
    app.set('view engine', 'handlebars');
    // Define a route inside express,
    // "get" refers to an HTTP method,
    // in the callback function 
    // "req" refers to a request object and
    // "res" refers to a response object
    app.get('/', function(req, res) {
    // For Cloud 9 I must use port 5000 (see below)
    // and for other apps the port is usually 80
    // Code below means listen to the default port number number 
    // provided by the server (Cloud) or 5000, if none is provided,
    // convert this into a number type, and assign it to a "port" variable
    var port = Number(process.env.PORT || 5000);
    // app listens to traffic on port 5000
  3. Create a base.handlebars file located at /views/layouts/base.handlebars with the following code:
    <!DOCTYPE html>
        <meta charset="utf-8" />
        <title>Example App</title>
        <hr />
        This is a handlebars comment and
        code below outputs HTML from 
        res.render in server.js file
  4. Create a home.handlebars file located at /views/home.handlebars with the code listed below:
    <h2>home.handlebars View Here</h2>

Leave a Reply

To Top ↑