Node.js E-Commerce with Harp JS & Snipcart

If we've learned one thing these last few years, it's that developers are getting tired of putting up with closed ecosystems, clunky backends, and heavy databases. This frustration, coupled with the rise of client-side possibilities, made way for the JAMstack revolution (JavaScript, APIs, & Markup). As a result, an exponential number of developers are now using static site generators.

At Snipcart, we've also played around with them, a lot. Whether with Jekyll, Hugo, or many others, we've created a bunch of demo sites and cart integrations on top of static sites.

Note: If you're new to the whole static/JAMstack development phenomenon, we strongly advise giving this Smashing Magazine post a read.

Recently, we published a post telling developers to learn vanilla JS before frameworks. In it, we touched on the awesomeness of Node.js a bit. A good friend of ours, knowing how much we liked static site generators, pointed us to a Node.js-powered tool he thought we'd enjoy: Harp JS.

I immediately took it upon myself to craft a Harp JS tutorial for our blog. So in this post, I'm going to show how easily Node.js e-commerce can be handled on a static site with Harp JS.

First, a few definitions.

What is Node.js?

Basically, Node.js is an event-driven JavaScript runtime environment—so, yeah, server-side, browser-less JS execution. It's lightweight, efficient, and boasts the most popular open source package ecosystem in the world: npm.

Why is it awesome, you ask? To quote Isaac Lewis in his cool post on using Harp JS / Node.js:

"This is why I love Node.js: Instead of having to install PHP and MySQL and Apache, you just install Node + a few packages, and we're running a local server in minutes, instead of days."

The community around Node is huge; it's become the #1 choice for many developers putting together killer server-side applications.

What is Harp JS?

Harp JS is a Node.js open source static web server with built-in preprocessing. Since it serves Jade, Markdown, EJS, CoffeeScript, Sass, LESS and Stylus as HTML, CSS & JavaScript without requiring any configuration, it has become very popular in the static web dev community.

Oh, and it also plays well with BrowserSync & Gulp.

All right, so now, I'm going to walk you through a Harp static shopping cart set up. By the end of this post, we'll have a nice Node.js e-commerce set up thanks to Harp & Snipcart.

Precondition

I'll assume you've already played around with Harp JS a bit. If not, you can read the in-depth post developer Matt Lambert wrote a while ago about how to use Harp's static web server.

You'll also need a Snipcart account. Development is forever free in test mode; you can sign up here.

1. Installing Harp JS and initializing your e-commerce site

First, you will have to install Harp and initialize a project. Of course, there's a handy little Node.js npm package to do just that:

npm install -g harp
harp init snipcartdemo

The second command will generate a basic Harp project that you could already serve if you wanted to.

2. Adding the Snipcart API Key into your Harp project

We will add our Snipcart API key (found under Account > API Keys in your merchant dashboard) in the global config before we start the local server.

To do so, you will create a harp.json file in your project's root directory.

Here's what we will put in the new JSON file:

{
    "globals": {
        "snipcartApiKey": "YjdiNWIyOTUtZTIyMy00MWMwLTkwNDUtMzI1M2M2NTgxYjE0"
    }
}

By declaring the API key this way, Harp will make this variable public so any page can access it.

You can now boot up the server so we can play around a little! This command, using your project name, will do the trick:

 harp server snipcartdemo

3. Creating products and appropriate layouts

Now that everything is up and running, let's put some meat on this e-commerce bone!

We will create a products folder that will contain both the data and the layout templates related to the products.

Now, create a _data.json file in this new products folder.

We put the low dash in front of the file so it won't be served publicly—a Harp convention. This is where any information regarding the products will reside.

Here's our file for the demo:

{
  "product1": {
    "name": "Ski Goggles",
    "id": "1",
    "image": "https://snipcartweb-10f3.kxcdn.com/media/9896/harpjs-shopping-cart-ski-goggles.jpg",
    "description": "Clear lens, perfect for night runs in the park.",
    "url": "/",
    "price": "120.00"
  },
  "product2": {
    "name": "Lightweight Helmet",
    "id": "2",
    "description": "Subtle style with secure, tested shock protection.",
    "image": "https://snipcartweb-10f3.kxcdn.com/media/9897/harpjs-shopping-cart-ski-helmet.jpg",
    "url": "/",
    "price": "100.00"
  },
  "product3": {
    "name": "Pipe Gloves",
    "id": "3",
    "description": "Lean, slick and grippy as can be.",
    "image": "https://snipcartweb-10f3.kxcdn.com/media/9899/harpjs-shopping-cart-pipe-gloves.jpg",
    "url": "/",
    "price": "80.00"
  }
}  

Okay, so let's create a template to show this product data.

We will stay in the same folder (products) and create a _product.jade file.

In the following examples, we're going to use the jade templating engine; we're big fans here at Snipcart. ;) But if you feel more comfortable with more HTML-like templating engines, we suggest you take a look at EJS. It can be used with Harp out of the box.

Here's the template we will be using:

div.product-details
  img(src=image)
  div.product-description 
    p #{ content } 
    
    button.snipcart-add-item(
      data-item-name=name
      data-item-id=id
      data-item-image=image 
      data-item-url=url
      data-item-price=price
      data-item-description=description)
      Buy it for #{ price } 

You'll see further down how this simple products layout looks!

4. Injecting the actual frontend shopping cart

Now, let's generate a partial including all the necessary scripts for Snipcart.

We will create a new Snipcart folder, and nest a _snipcart.jade file in it.

Here's ours:

     script(src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js")
     
     script(src="https://cdn.snipcart.com/scripts/2.0/snipcart.js" data-api-key=snipcartApiKey id="snipcart")
     
     link(href="https://cdn.snipcart.com/themes/2.0/base/snipcart.min.css" rel="stylesheet" type="text/css")

As you can see, for the data-api-key, we are not hard coding the key there, but rather using the global variable we defined earlier.

5. Putting the final touches on your Harp JS e-commerce site

Almost there, folks! What we want to do now is use everything we created to bring our little demo store to life. We'll keep everything simple and use the default index page to do so.

First, we'll put our partial that contains the scripts, and then iterate through our products data and render a product template for each.

Here's what it looks like in code:

h1 Harp store powered by Snipcart

!= partial("./snipcart/_snipcart.jade")

div.products
    for product in public.products._data
        != partial("./products/_product", product)

And voilà:

nodejs-ecommerce-harpjs-snipcart

Go ahead, check out the live demo!

And also, all of the code used for this integration is available in this GitHub repo.

Conclusion

I truly had a blast crafting this lean Node.js e-commerce site with Harp JS & our shopping cart platform.

Altogether, reading the Harp JS docs + creating the templates and data took me about an hour or two. Yeah, it took me quite some time to understand that you had to restart the server to access newly created globals. ;)

The Harp JS documentation was helpful and went straight to the point. And preprocessing out-of-the-box was a bliss (setting up the stack with a bash command only).

Of course, we could have pushed the integration a bit further. For instance: creating a custom layout showing a cart icon with products count, or displaying a single page for every product.

I sincerely hope this post convinced you to start playing with Harp JS and/or explore the modern static web dev and JAMstack possibilities around you. And if you ever use Snipcart to enable e-commerce on your static project, shoot us an email at geeks@snipcart.com. We'd like to check it out, and maybe feature it somewhere if it's good, inspiring stuff for our community!

We're always publishing cool technical and editorial posts for devs such as this one, so feel free to subscribe to our newsletter to stay in the loop!*


Found this post entertaining or valuable in any way? Take a sec to send a tweet our way. We'd love that! Got any questions or comments regarding Node.js, static web dev, Harp JS, or Snipcart? Hit the section below!

Suggested posts: