Adding eCommerce Functionality in Hugo with Snipcart
- Author: Md. Saad
- Published at: October 25, 2023
- Updated at: October 25, 2023
In today's digital age, establishing an online presence for your business is essential to reach a broader customer base and increase revenue. If you've built your website using Hugo, a popular static site generator known for its speed and simplicity, you may be wondering how to incorporate eCommerce functionality seamlessly.
Fortunately, Hugo's flexibility allows for the integration of various eCommerce solutions, and one such powerful option is Snipcart. Snipcart is a JavaScript-based shopping cart platform that can be effortlessly integrated into Hugo websites, transforming your static site into a fully functional eCommerce platform. Whether you're selling physical products, digital downloads, or services, Snipcart offers a user-friendly and customisable solution that requires minimal development effort. In this guide, I will walk you through the process of adding eCommerce functionality to your Hugo website using Snipcart.
Sign Up for Snipcart
Go to the Snipcart Website and sign up for an account if you don't already have one.
Create a Hugo Project
Make sure you have Hugo installed on your local machine. You can create a new Hugo site using the command “hugo new site my-hugo-website”. Here “ my-hugo-website” will be the site name:
Install Snipcart to your Hugo Site
To install Snipcart into your website, copy the HTML code snippet provided below and paste it directly into your website's code. It can be added immediately after the opening <body> tag or before the end of the </body> tag in your website's markup.
<script>
window.SnipcartSettings = {
publicApiKey: "YOUR_API_KEY",
loadStrategy: "on-user-interaction",
};
(function(){var c,d;(d=(c=window.SnipcartSettings).version)!=null||(c.version="3.0");var s,S;(S=(s=window.SnipcartSettings).timeoutDuration)!=null||(s.timeoutDuration=2750);var l,p;(p=(l=window.SnipcartSettings).domain)!=null||(l.domain="cdn.snipcart.com");var w,u;(u=(w=window.SnipcartSettings).protocol)!=null||(w.protocol="https");var m,g;(g=(m=window.SnipcartSettings).loadCSS)!=null||(m.loadCSS=!0);var y=window.SnipcartSettings.version.includes("v3.0.0-ci")||window.SnipcartSettings.version!="3.0"&&window.SnipcartSettings.version.localeCompare("3.4.0",void 0,{numeric:!0,sensitivity:"base"})===-1,f=["focus","mouseover","touchmove","scroll","keydown"];window.LoadSnipcart=o;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",r):r();function r(){window.SnipcartSettings.loadStrategy?window.SnipcartSettings.loadStrategy==="on-user-interaction"&&(f.forEach(function(t){return document.addEventListener(t,o)}),setTimeout(o,window.SnipcartSettings.timeoutDuration)):o()}var a=!1;function o(){if(a)return;a=!0;let t=document.getElementsByTagName("head")[0],n=document.querySelector("#snipcart"),i=document.querySelector('src[src^="'.concat(window.SnipcartSettings.protocol,"://").concat(window.SnipcartSettings.domain,'"][src$="snipcart.js"]')),e=document.querySelector('link[href^="'.concat(window.SnipcartSettings.protocol,"://").concat(window.SnipcartSettings.domain,'"][href$="snipcart.css"]'));n||(n=document.createElement("div"),n.id="snipcart",n.setAttribute("hidden","true"),document.body.appendChild(n)),h(n),i||(i=document.createElement("script"),i.src="".concat(window.SnipcartSettings.protocol,"://").concat(window.SnipcartSettings.domain,"/themes/v").concat(window.SnipcartSettings.version,"/default/snipcart.js"),i.async=!0,t.appendChild(i)),!e&&window.SnipcartSettings.loadCSS&&(e=document.createElement("link"),e.rel="stylesheet",e.type="text/css",e.href="".concat(window.SnipcartSettings.protocol,"://").concat(window.SnipcartSettings.domain,"/themes/v").concat(window.SnipcartSettings.version,"/default/snipcart.css"),t.prepend(e)),f.forEach(function(v){return document.removeEventListener(v,o)})}function h(t){!y||(t.dataset.apiKey=window.SnipcartSettings.publicApiKey,window.SnipcartSettings.addProductBehavior&&(t.dataset.configAddProductBehavior=window.SnipcartSettings.addProductBehavior),window.SnipcartSettings.modalStyle&&(t.dataset.configModalStyle=window.SnipcartSettings.modalStyle),window.SnipcartSettings.currency&&(t.dataset.currency=window.SnipcartSettings.currency),window.SnipcartSettings.templatesUrl&&(t.dataset.templatesUrl=window.SnipcartSettings.templatesUrl))}})();
</script>
Now, replace YOUR_API_KEYinside the snippet with your public API key. It can be found inthis section of our dashboard. For more configuration, visit the snipcart documentation.
Add a JSON file for Storing Products
As I have already added Snipcart to our project, let’s add some products. For the simplicity of this post, I'll generate a static .json file to store our product data. To proceed, you must create a new file named 'products.json' in the 'data' folder. This file will serve as the container for our product data. The file should look like the following codes:
[
{
"id": "1",
"name": "KIO-TAPE BRAND",
"price": 34.87,
"image": "images/projects/project-thumb-four.jpg",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
"customnName": "Frame Color",
"options": ["Black", "Blue"],
"url": "https://test-hugosite.netlify.app/"
},
{
"id": "2",
"name": "SEAMLESS WATCH",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ",
"price": 145.98,
"image": "images/projects/project-thumb-three.jpg",
"customnName": "Frame Color",
"options": ["Black", "Red"],
"url": "https://test-hugosite.netlify.app/"
}
,
{
"id": "3",
"name": "OSEN CLOCK",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ",
"price": 145.98,
"image": "images/projects/project-thumb-two.jpg",
"customnName": "Frame Color",
"options": ["Yellow", "Red"],
"url": "https://test-hugosite.netlify.app/"
}
]
Note: Snipcart products are defined directly within HTML markup using data attributes. For more information, you can find the specifics here.
Show Products on the Hugo Site
Hugo offers a convenient function called getJSON, which proves especially useful when you're dealing with data from sources like headless CMS platforms or APIs that provide data in JSON format.
In our case, since our JSON file is located directly within the 'data' folder, we could have used .Site. Data.Products or getJSON method. However, use the getJSON method to show how to interact with remote APIs.
First, create a layouts/partials/product.html. Your code should look like this:
{{ $products := getJSON "/data/products.json" }}
<section class="products">
<div class="container">
<div class="row">
{{ range $products }}
<div class="col-md-4 mb-5">
<div class="card w-100">
<div class="card-image">
<img src="{{ .image | absURL }}" alt="image" class="card-img-top w-100">
</div>
<div class="card-body">
<h5 class="card-title">{{ .name }}</h5>
<p class="card-text">{{ .description }}</p>
<p class="card-text">{{ .customnName }} : <strong>{{ delimit .options ", " }}</strong></p>
<button
class="snipcart-add-item btn btn-sm btn-primary"
data-item-id="{{ .id }}"
data-item-name="{{ .name }}"
data-item-price="{{ .price }}"
data-item-image="{{ .image | absURL }}"
data-item-description="{{ .description }}"
data-item-url="{{ .url | absURL }}"
data-item-custom1-name="{{ .customnName }}"
data-item-custom1-options="{{ delimit .options "|" }}"
>
Add to cart
</button>
</div>
</div>
</div>
{{end}}
</div>
</div>
</section>
All “data-item-**” attribute inside the <button> tag will be shown on the cart page. Finally, add the product page to your layouts/index.html. Your code should look like this:
{{ define "main" }}
{{ partial "product.html" . }}
{{ end }}
Styling Your Site
I have used Bootstrap to style buttons and other items. However, you can use any CSS framework you want.
I have also used the default cart template of Snipcart, which is the full-page cart. However, you can use the other one, which is a side modal. The default style is the full-page cart. For more details, you can read here.
Testing Your Site Locally
Run your Hugo site locally using Huogserver and test the eCommerce functionality by adding products to the cart and going through the checkout process. If you face any errors in the checkout process, please read the full documentation from Store Set Up to set up your store correctly.
Deploy Your Site
Once you're satisfied with the setup, deploy your Hugo site to your hosting provider of choice. I have decided to deploy our Hugo demo using the amazing service at Netlify. You can learn how to deploy a Hugo site.
That's it! You've successfully added eCommerce functionality to your Hugo website using Snipcart. Your customers can now browse products, add them to the cart, and complete their purchases through the Snipcart checkout system.
Are you feeling unsure about where to begin? Search no more, because Staticmania is here for you! Our committed team of specialists is ready to lead you through every step of the journey. Don't hesitate to reach out to us now to commence your journey.