Sometime, somehow we have wanted to put up a static website and host it somewhere quick, no frameworks, no “2017 latest web tech” to build it with. Just plain HTML and CSS; maybe some JavaScript, nothing too complex.

NOTE: In order to send messages to Pusher a server component is necessary. Github pages (or any other static hosts) will not allow you to have a real server. Therefore, to get one running, you can deploy the server that we will be creating in this article to Heroku.

It may be a single page portfolio site, listings for an event or a blog and the need for a Static Site Generator(SSG) is required. Instead of using Jekyll (built with Ruby), we choose Metalsmith because it is built with JavaScript. In this article, we are going to see how to add realtime comment system to a static Metalsmith-driven blog using Pusher. We use Pusher to render realtime comments on posts.

Here is a glimpse of what we will be building:

What is MetalSmith?

Simply put, metalsmith is a light-weight and extremely pluggable static site generator. When I say extremely pluggable, it just has more to do with ready made awesome plug-ins than HTML! Get that yet? Read on!

Using MetalSmith is pretty straightforward, simply create a source folder with source files in it written with markdown, metalsmith manipulates the files with the aid of plug-ins and converts the files to plain HTML in a destination folder ready to be served. Here’s an outline of how it really works:

  • Create markdown files in a source folder.
  • MetalSmith converts it to a JavaScript object.
  • metalsmith applies set of manipulations in the form of plug-ins already supplied.
  • metalsmith outputs the manipulated file as an HTML file to be served.

Installation

I assume you have Node installed as well as npm so create a project folder like metalsmith-blog, and change directory to the project folder.

    mkdir metalsmith-blog && cd metalsmith-blog

run


    npm init
    npm install metalsmith --save

These create a package.json file. We can see the metalsmith already included as a dependency in the package.json file.

In the project folder (root), create the folders src and build. The src folder would hold the source files (HTML, CSS and JS) whereas the build folder serves as the destination for the transformed source files.

Let’s install the necessary plug-ins. It’s getting sweet!

    npm install --save metalsmith-collections metalsmith-markdown metalsmith-assets metalsmith-templates metalsmith-permalinks jade

In brief:

  • metalsmith: Installs Metalsmith
  • metalsmith-markdown: Converts markdown files written in source to HTML
  • metalsmith-templates: Enables the use of templates like Jade/Pug for layouts
  • metalsmith-assets: Includes static assets like CSS and JavaScript
  • metalsmith-permalinks: Customize permalink of files
  • metalsmith-collections: Helps you generate grouped content list for pages like Home
  • jade: preferred template engine for Metalsmith

There are a whole lot of plug-ins, thanks to the awesome metalsmith development community, you can find them here.

We got the basic folders now, and our package.json file looks like:

    {
      "name": "realtime-static-metalsmith",
      "version": "1.0.0",
      "main": "index.js",
      "license": "MIT",
      "scripts": {
        "serve": "serve build",
        "build": "node build.js",
      },
      "dependencies": {
        "jade": "^1.11.0",
        "metalsmith": "^2.3.0",
        "metalsmith-assets": "^0.1.0",
        "metalsmith-collections": "^0.9.0",
        "metalsmith-markdown": "^0.2.1",
        "metalsmith-permalinks": "^0.5.0",
        "metalsmith-templates": "^0.7.0",
      }
    }

Note the "``scripts``" property which was included. To serve the project on your local network, you must have serve installed else install it with:

    npm install serve --save-dev

Assign the value of "``serve build``" to the "``serve``" property so whenever we run serve in the command line, the build folder is served to our local network! Also the value "``node build.js``" is assigned to the property "``build``", this ensures that when we run

    npm run build

in the command line, the build.js file is run.

Note: The build.js file hasn’t been created yet.

Lets get to creating the files!

Build Script for Metalsmith

Create the file build.js in the root directory, this serves as the engine of the site, as all the plug-ins are to be configured here. It’s built as thus:

1 – Load the plug-ins

    var metalsmith  = require('metalsmith');
    var markdown    = require('metalsmith-markdown');
    var templates  = require('metalsmith-templates');
    var permalinks = require('metalsmith-permalinks');
    var collections = require('metalsmith-collections');
    var assets = require('metalsmith-assets');

2 – Call the metalsmith function metalsmith() and chain all the plug-ins loaded to it with the use() method, passing their required arguments as well.

Take note of the order in which the plug-ins are passed as the source files will be manipulated in that order.

    metalsmith(__dirname)
      .source('src')
      .use(collections({
        articles: {
          pattern: 'articles/**/*.md',
          sortBy: 'date',
          reverse: true
        }
      }))
      .use(markdown({
        gfm: true,
        tables: true,
      }))
      .use(assets({
        source: 'src/assets/',
        destination: './'
      }))
      .use(permalinks())
      .use(templates({
        engine: 'jade',
        directory: 'templates'
      }))
      .destination('build');

Note the source and the destination directories. For this article, we used Jade as the templating tool. Feel free to try something else!

3 – Error Handling in case of build error

    ...
    .destination('build')
    .build(function (err) {
        if (err) {
          throw err;
        }
      });

Home and Article Layout with Jade

Jade is used as the templating engine to pre-process the HTML to be written. Install Jade with:

    npm install --save jade

Create an article.jade file in the templates folder to server as a layout template for markdown articles:

    html(lang='en')
      head
        meta(charset='utf-8')
        meta(http-equiv='X-UA-Compatible', content='IE=edge,chrome=1')
        meta(name='viewport', content='width=device-width')
        title= title
        link(rel="stylesheet", href="/css/styles.css" type="text/css")
        link(rel="stylesheet", href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css")
      body
        .container-fluid#app
          a(href="/index.html" style="text-decoration:none")
            h1.text-primary.text-center Raccoon Blog
          .main(style="margin:50px 20%")
            h2= title
            p.text-info= author
            div.timestamp= date
            br
            article!= contents
            article-comment
        script(src="https://unpkg.com/vue")
        script(src="https://js.pusher.com/4.1/pusher.min.js")
        script(src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.js")
        script(src="/js/app.js")

Create another jade file in for the Home page layout named index.jade in the same template directory:

    html(lang='en')
      head
        meta(charset='utf-8')
        meta(http-equiv='X-UA-Compatible', content='IE=edge,chrome=1')
        meta(name='viewport', content='width=device-width, initial-scale=1')
        title= 'Raccoon Blog'
        link(rel="stylesheet", href="css/styles.css" type="text/css")
        link(rel="stylesheet", href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css")
      body
        .container-fluid
          h1.text-primary.text-center Raccoon Blog
          p.text-center A blog by Christian Nwamba
          .main
            each article in collections.articles
              article.content-article
                header
                  p
                    span.timestamp= article.date
                  h3
                    a(href='/' + article.path)= article.title
                hr

The both article have some common features — same stylesheets and head elements. The article layout displays a single article while the index layout displays a collection of articles.

In the src directory, create an index.html file — this is the root HTML and it is the entry point for the Metalsmith project. The content just points to the index.jade:

    ---
    template: index.jade
    ---

Adding Article Pages

To start seeing articles in action, create a src/articles/ directory. The markdown files for our articles will be in this folder.

To test that the articles are generated, create two example MD files in the src/articles folder you just created with an example content like the following:

**welcome.md**

    ---
    title: An intro to Lorem Ipsum Text.
    date: 2017-08-29 00:01
    author: by Christian Nwamba
    template: article.jade
    ---
    **Lorem Ipsum for the gods**
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

and the second:

**helloworld.md**

    ---
    title: Section 2 of Lorem Ipsum.
    date: 2017-08-29 12:28
    author: by William Imoh
    template: article.jade
    ---
    **Section 2**
    Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet...

We have the front-matter on top, this contains details of the blog post and is used by article.jade during preprocessing. The front-matter is a list of meta information about a particular document. MetalSmith picks the information up and uses it to dynamically generate a layout for each article.

Run the build command to generate output

    npm run build

Swoosh! The source files in markdown have been converted to HTML files in the build directory. Serve the build directory with:

    npm serve build

Now relieve the joy of seeing your static blog serving on localhost! Here is what it looks like:

Now click on one of the articles and you should see something like:

Lets get to the more fun part.

Creating comments with Vue

You didn’t see that coming yeah, not to worry, we wouldn’t go too deep into Vue. We only need to create the Javascript file app.js in /src/assets/js. In /template/article.jade we import Vue at the bottom of the script from a CDN by putting in,

    script(src="https://unpkg.com/vue")
    script(src="/js/app.js")

The second script tag links the local JavaScript file to the jade template.

App.js

In app.js, a new Vue instance was created with a Vue component (article-comment). This component contains the template for the comment form as well as event functions to handle submission and on-screen display of comments. Check it out here.

    var articleComment = {
      template:  `
        <div>
          <h3>Comments</h3>
          <div class="form-group">
            <input type="text" class="form-control" placeholder="Name" v-model="name" />
          </div>
          <div class="form-group">
            <textarea class="form-control" placeholder="Comment here..." v-model="content"></textarea>
          </div>
          <button class="btn btn-info" @click="onSubmit()">Submit</button>
          <h4 v-if="comments.length > 0">Existing comments</h4>
          <div class="list-group">
            <a class="list-group-item" v-for="comment in comments">
              <h4 class="list-group-item-heading">{{comment.name}}</h4>
              <p class="list-group-item-text">{{comment.content}}</p>
            </a>
          </div>
        </div>
      `,
      data() {
        return {
          comments: [],
          name: '',
          content: ''
        }
      },
      methods: {
        onSubmit: function() {
          this.comments.push(
            {name: this.name, content: this.content}
          )
          this.name = '';
          this.content = '';
        }
      }
    }
    var app = new Vue({
      el: '#app',
      components: {
        'article-comment': articleComment
      }
    })

Here’s what actually happens:

  • Once a comment is created and the submit button is clicked, the onSubmit() method is called.
  • The name and content variables are updated with the name and comment in the form input.
  • The name:content pair is pushed into Vue’s comment array.
  • These valued are passed to the DOM via Vue template.

Run:

    npm run build
    npm serve build

Notice that the JavaScript folder and file has been created in /build/assets. That is how seamless metalsmith can be.

Now we can create comments and have them display on-screen!

Is this the best part yet? Hell no! Lets get to it.

Implementing Realtime comments display with Pusher

Why Pusher?

Being leaders in realtime technology, Pusher gives us the power to implement realtime features in our blog with their simple hosted API.

Create a pusher account

Go on to Pusher and create an account. Create a new app and obtain an app key, this would come in very handy soon enough.

Install Pusher and Axios

Pusher is installed in two parts, the clients-side and the server side. For the client side we install pusher and Axios by importing the script with:

    script(src="https://js.pusher.com/4.1/pusher.min.js")
    script(src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.js")

Axios enables us make HTTP requests to our local node server. There lots of alternatives to Axios but we are sticking to it because of it’s simplicity and the promise based API.

Update Vue App with Pusher Realtime Features

Now we have to update the /src/assets/js/app.js file to include server configurations for the node server.

First, two new variables will be added to the data() method and assigned a value of null. This is to ensure that the pusher and channelName variable are accessible in the Vue instance.

    data() {
        return {
          comments: [],
          name: '',
          content: '',
          pusher: null,
          channelName: null,
        }
      },

We want to configure Pusher immediately Vue is loaded. To do so, we configure Pusher in Vue’s created lifecycle method and pass the value to the pusher property:

    new Vue({
    ...
      created() {
        this.pusher = new Pusher('PUSHER-KEY', {
          encrypted: true
        });
    ...
    }) 

also channelName is assigned the path of any article in view with:

    this.channelName = window.location.pathname.replace(new RegExp('/', 'g'), '-');

The path assigned is modified to use a dash( – ) to indicate paths instead of forward slash ( / ). This is because pusher channel names doesn’t recognize paths with strokes but with dashes.

A variable channel with a local scope in the method is created and is assigned the result of calling the pusher.subscribe() **method with this.channelName as parameter.

channel is bound to the response received from the server new-comment, and passed a callback function with an argument comment which is the data from the response.

This data is parsed and pushed into the comments array on the Vue instance!

    this.channelName = window.location.pathname.replace(new RegExp('/', 'g'), '-');
    var channel = this.pusher.subscribe(this.channelName);
    channel.bind('new-comment', (comment) => {
      this.comments.push(
        {name: comment.name, content: comment.content}
      )
    });

Now, the method onSubmit() still doesn’t feel right as we still can’t be handling form submissions locally without sending data over to the server right?

We need to send POST request to the server so that Pusher can emit realtime events to all connected clients.
To do so, simply send a POST request with the form values to the server using axios:

    onSubmit() {
       const payload = {name: this.name, content: this.content, channel: this.channelName};
       axios.post('http://localhost:2000/comment', payload)
          .then(response => {
            console.log(response);
          })
    }

Configure Server

On the server side, In addition to pusher there are other dependencies required to build our realtime feature, they are Body-Parser, CORS and Express Server. We install these with:

    npm install --save body-parser pusher cors express

These dependencies are added to our package.json file and it looks like this:

    {
      "name": "realtime-static-metalsmith",
      "version": "1.0.0",
      "main": "index.js",
      "license": "MIT",
      "scripts": {
        "serve": "serve build",
        "build": "node build.js",
        "watch": "nodemon --ignore build/ build.js",
        "server": "node server.js"
      },
      "dependencies": {
        "body-parser": "^1.17.2",
        "cors": "^2.8.4",
        "express": "^4.15.4",
        "jade": "^1.11.0",
        "metalsmith": "^2.3.0",
        "metalsmith-assets": "^0.1.0",
        "metalsmith-collections": "^0.9.0",
        "metalsmith-markdown": "^0.2.1",
        "metalsmith-permalinks": "^0.5.0",
        "metalsmith-templates": "^0.7.0",
        "pusher": "^1.5.1"
      }
    }

In our root folder, we should create a node server (server.js) and configure it as given below:

    //Load tools
    const express = require('express');
    const bodyParser = require('body-parser')
    const Pusher = require('pusher')
    const cors = require('cors')

    const app = express();

The build tools are first loaded, then we configure the express server using cors and bodyParser as such:

    //configure Express
    app.use(cors())
    app.use(bodyParser.urlencoded({ extended: false }))
    app.use(bodyParser.json())

Next up is configuring pusher using app details obtained during account creation on Pusher:

    const pusher = new Pusher({
      appId: 'PUSHER-ID',
      key: 'PUSHER-KEY',
      secret: 'PUSHER-SECRET',
      encrypted: true
    });

Now to the most important part, configuring the express route. On receiving a POST HTTP request for a new-comment, the request body is logged on the console, we use the trigger method to open a Pusher channel based on the channel value on the req.body object. The event is named new-comment and the payload sent from the client is sent out to all connected clients via that channel. Lastly the server is created to listen on port 2000 of our localhost!

    app.post('/comment', (req, res) => {
      console.log(req.body);
      pusher.trigger(req.body.channel, 'new-comment', req.body);
      res.send('Pushed');
    })

    app.listen(2000, () => console.log('Listening at 2000'));

To run the server, you can update your package.json include a run script for sever.js:

    "scripts": {
      "server": "node server.js"
    }

Execute the following to rebuild the Metalsmith app:

    npm run build

Then use this to start the sever:

    npm run server

Here is what the realtime comments look like:

We now have our blog listening for comments. To try this out, open a separate browser, run an instance of the blog on the browser, add a new comment in the previous browser and watch it update in the new browser…in real time!

You can find the full build here.

Conclusion

It has surely been awesome building a static blog with metalsmith, using Vue for the comments and Pusher for the realtime updating of the comments.
Feel free to add your styles to the blog. Try out other templating engines too, maybe pug. Also play around with other MetalSmith plug-ins. Have fun.

About Chris Nwamba

Chris is a JavaScript preacher. He also strives to make something out of other languages. Tech Writer. Dev Evangelist. Speaker.