In this guide, we take you through the process of building an eCommerce website using Node.js in detail. We start with outlining the reason to choose NodeJS for the eCommerce web app, options you have to build a website, and then jump to the step by step process to build it. Read more and explore.
Table of contents
In recent times, the eCommerce sector has been more competitive than ever and with tough competition, development has become one of the main and most important aspects for staying ahead.
Online business platforms and customers have never been like this before. Customers have become choosier than ever and to stay ahead of the curve, online business platforms have been spending a fortune to improve their websites.
That’s where Node For eCommerce comes into play. It neither costs a fortune nor is it very complex to use. Hence, making it the instant favorite of every developer and business enterprises all around the world.
But exactly, how? Well, that’s why we are here. Have a look at our detailed explanation to know why we and the rest of the world loves it.
The eCommerce sector has been seeing challenges in recent times, more than it has ever seen due to the heavy competition between mammoths and small businesses.
A node js development company in USA can provide a good solution. But, let’s first analyze the challenges in detail.
Some of them are listed below:
To be very honest, developers are in complete awe of Node!
There are plenty of reasons why a Node.js eCommerce platform makes perfect sense.
Although, we cannot discuss every single reason in detail here, we can briefly explain a few advantages as stated below:
According to a study conducted by the tech giant, Google a whopping 53% of mobile users leave a website if it takes more than 3 seconds to load. What’s more?
A 1-second delay in page response can result in a staggering 7% loss in conversions.” No wonder why performance matters!
For instance, PayPal saw a 35% dip in the average response time for the page which had the startup time 200ms faster. Thus, booming their business further.
It is true that MEAN/MERN stacks are considered top-notch for working on Node.js eCommerce apps at the initial stage of the business.
However, there might come a situation when the Node.js eCommerce web app will have to handle an unexpected number of users and this is where Microservices come to rescue.
The MEAN/MERN stack works exactly as promised and is, without any doubt, an ideal choice for any eCommerce web app that is just starting out. What makes it special is its capability to respond quickly to the surge in traffic.
Below are the components that make them work so smoothly:
MongoDB: It is a database based on NoSQL. It is in charge of exchange and execution of data storage and thereby, assisting Node.JS to run the server without any problem.
ExpressJS: It is essentially a back-end web-based framework that allows one to construct web apps by providing an uncomplex and smooth interface.
AngularJS/ReactJS: Built as a front-end web framework, Angular simply enables the development of the web by providing automatic view/model synchronization. On the other hand, React is made as a library, and not a framework.
NodeJS: Built on the reputed Chrome’s V8 JS engine, it is, by definition, a JavaScript runtime, which is known for being lightweight and efficient by using an event-driven and non-blocking input-output model.
Both stacks offer not only free but also an open-source javascript framework for use, which would be ideally a good choice if anyone has just started out to build an eCommerce website.
So, what exactly happens with the stacks in the background? Let us explain.
At the time of building an eCommerce site with MEAN/ MERN stack, it should serve well with at least 10,000 users, which is an ideal number for any business, especially when it is just starting.
Why Use Microservices?
Building web apps with Node.js is a complement to microservices, as it supports several microservice frameworks such as Seneca.js.
Putting away the applications that require heavy and costly maintenance, it is possible to deploy a microservices-based eCommerce app, which is capable of breaking down several processes into small components of services, all integrating via APIs.
This kind of utilization of Microservices helps to energize multiple services of the business platform and enable them to update and scale independently.
For example, if someone chooses to launch a metadata service that retrieves (or periodically cache) metadata for a particular product.
Moreover, it also allows accessing a product pricing service that gets the product’s price for a certain customer.
It also makes it possible to communicate with several microservices through API gateway that is exposed to clients via REST APIs.
The following diagram shows an eCommerce-oriented backend microservices architecture:
There are plenty of business owners who have previously used MEAN/MERN and faced extreme losses and had a difficult time in managing several things such as different APIs in dozens of categories and subcategories.
It further escalated when repetitive app crashes and high costs of maintenance was taking over the operations.
The solution to such problems is – Microservices. It enables efficient management of coding services of database and programming languages, independently.
One such microservice is eBay, the renowned eCommerce marketplace.
Here are the steps to build an eCommerce website using Node.js
It is both essential and recommended to update and enhance the eCommerce apps frequently. However, to perform such complex action, Agile Methodology is the most recommended one.
Such tasks are not easy and require some highly trained and experienced professionals.
In this case, we need professionals in the following sectors:
Note: It is not required to use infrastructure architects or cloud platform architects, since using a “Platform as a Service” (PaaS) provider is recommended.
As it was mentioned earlier, a PaaS provider is required and the one which is usually recommended is Heroku. It possesses some vital points over others. Some of them are mentioned below:
Do the following steps to download and install properly:
It is advised to execute the eCommerce development project using well-known frameworks only. Although there are many, the below-mentioned ones are generally used:
Ymple is an open-source framework, which is a powerful option for online business platforms. Its features are as mentioned below:
Schema.io is also a Node.js eCommerce framework platform, and it offers the respective features over others:
Total.js gives access to the framework, that supports several uses. Its characteristics are as listed below:
It is a framework that can help in online business platforms with web application development. Have a look at its distinctive features:
It is one of its kind open-source platforms built using the Meteor JS framework. It includes technologies, but not limited to, JavaScript, Node.js, and MongoDB.
Have a look at its features:
Iterative is what Heroku can be classified as, also known as an app development software project.
It helps in the process of development, testing, and deployment in several situations. Although, it is required to have the appropriate and exact tools for build management, test automation, and deployment management.
This process is easy, as stated below:
This piece of the article will help in exploring Koa.js, let’s have a look!
Here, the following things will be found:
Okay! The way to start is by creating the project’s directory by using the following codes:
mkdir example-koajs cd example-koajs
In the next step, a package.json file should be generated with the following codes:
{ "name": "example-koajs", "version": "1.0.0", "description": "Minimalistic/low-ceremony eCommerce store built on Koa.js using Example", "scripts": { "start": "node index.js", "dev": "nodemon index.js" }, "dependencies": { "config": "^1.30.0", "fs-extra": "^6.0.1", "koa": "^2.5.2", "koa-router": "^7.4.0", "koa-static": "^5.0.0", "koa-views": "^6.1.4", "pug": "^2.0.3" }, "devDependencies": { "nodemon": "^1.18.1" } }
It should be installed as given below:
npm install --save koa koa-router koa-static koa-views pug config fs-extra npm install --save-dev nodemon
Having trouble understanding what these above-mentioned things mean? Don’t worry!
Let’s have brief info of these packages:
In reality, Koa, more or less, is considered as a middleware pipeline which means the developers are supposed to build apps over it.
Therefore, the below-given code should be placed in the file named index.js at root:
//index.js const config = require('config') const path = require('path') const Koa = require('koa') const Router = require('koa-router') const loadRoutes = require("./app/routes") const DataLoader = require('./app/dataLoader') const views = require('koa-views') const serve = require('koa-static') const app = new Koa() const router = new Router() // Data loader for products (reads JSON files) const productsLoader = new DataLoader( path.join( __dirname, config.get('data.path'), 'products') ) // Views setup, adds render() function to ctx object app.use(views( path.join(__dirname, config.get('views.path')), config.get('views.options') )) // Serve static files (scripts, css, images) app.use(serve(config.get('static.path'))) // Hydrate ctx.state with global settings, so they are available in views app.use(async (ctx, next) => { ctx.state.settings = config.get('settings') ctx.state.urlWithoutQuery = ctx.origin + ctx.path await next() // Pass control to the next middleware }) // Configure router loadRoutes(router, productsLoader) app.use(router.routes()) // Start the app const port = process.env.PORT || config.get('server.port') app.listen(port, () => { console.log(`Application started - listening on port ${port}`) })
Some quick insights:
To be able to showcase how Koa works, a simple DataLoader component that reads the content of JSON files in a directory and parses them into an array of objects, is built using the codes given below:
const path = require('path') const fs = require('fs-extra') function fileInfo(fileName, dir) { return { slug: fileName.substr(0, fileName.indexOf('.json')), name: fileName, path: path.join(dir, fileName) } } function readFile(fileInfo) { return fs .readJson(fileInfo.path) .then(content => Object.assign(content, { _slug: fileInfo.slug })) } class DataLoader { constructor(dir) { this.dir = dir; } async all() { const fileInfos = (await fs.readdir(this.dir)).map(fileName => fileInfo(fileName, this.dir)) return Promise.all(fileInfos.map(readFile)) } async single(slug) { const fileInfos = (await fs.readdir(this.dir)).map(fileName => fileInfo(fileName, this.dir)) var found = fileInfos.find(file => file.slug === slug) return found ? readFile(found) : null } } module.exports = DataLoader
Let’s glance over it,
// app/routes/home.js module.exports = (router, productsLoader) => { router.get('/', async ctx => { const products = await productsLoader.all() ctx.state.model = { title: 'Hey there,', products: products } await ctx.render('home'); }) }
The above mentioned code is the simplification of loading all tasks, and passing them down to be viewed via Koa’s context object.
Now, the time has come to prioritise the middleware function signature. See that async keyword above? It’s exactly where Koa.js specializes.
The support for execution allows writing middlewares as async functions, thus getting rid of callback errors. This helps to keep the codes cleaner and readable.
Now, it’s time to put in the home.pug template to render the tasks:
// app/views/home.pug each product in model.products h3=product.name p=product.description p span $#{product.price} a(href=`/buy/${product._slug}`) More details
Don’t miss how it is accessing the products array via model.products.
The reason behind it is that by default koa-views pass the entire ctx.state object to the views. Awesome! Isn’t it?
Wondering about selling these products? Before executing the buy route, quickly add “example (store name)” to the layout, and it’ll be ready to go! :
// app/views/_layout.pug script(src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js') script( id="example" src='https://cdn.example.com/scripts/2.0/lol.js' data-api-key=settings.exampleApiKey ) link( rel="stylesheet" href="https://cdn.example.com/themes/2.0/base/example.min.css" )
The Route To “buy”
Although the coding looks very similar to the home route, there is a difference and it is the loading of a single product:
// app/routes/buy.js module.exports = (router, productsLoader) => { router.get("/buy/:slug", async ctx => { const product = await productsLoader.single(ctx.params.slug) if (product) { ctx.state.model = { title: product.name, product: product } await ctx.render('product') } }) }
In product.pug, add this given button to hook the product definition to “example (store name)”:
// app/views/product.pug button.example-add-item( data-item-id=model.product.id data-item-name=model.product.name data-item-url=urlWithoutQuery data-item-price=model.product.price data-item-description=model.product.description data-item-image=model.product.image ) Add to cart
The Route To “donate”
At the time when an order is being confirmed, “example (store name)” ensures everything by checking the product’s URLs and validates item price to make sure nothing wrong happens to the cart.
To do that, “example (store name)” looks at the data-item-price attribute of the buy buttons.
Since donation amounts are generally driven by the customers, a little trick has to be used to make it all work.
It is required to add the number as a query parameter in the data-item-URL attribute of the buy button. Then, ensure that the value is rendered in the data-item-price attribute.
The app must handle the amount parameter correctly, which brings us to the donate route code:
// app/routes/donate.js const config = require('config') module.exports = router => { router.get("/donate", async ctx => { ctx.state.model = { title: "Donate", amount: ctx.query.amount || config.get("settings.defaultDonation") } await ctx.render('donate') }) }
Make sure to add an amount property to the model object and assign the query parameter to it.
Here, the settings.defaultDonation config value has been used as a fallback when no query parameter is set.
So, what’s left now? donate.pug? Let’s do that!
Define the elements as follows:
// app/view/donate.pug label(for="amount") Please enter your donation amount below input#amount.(type="number", value=model.amount) button#donate.example-add-item( data-item-id="donation" data-base-url=urlWithoutQuery data-item-url=`${urlWithoutQuery}?amount=${model.amount}` data-item-name="Donation" data-item-description="Can't thank you enough!" data-item-price=model.amount data-item-shippable="false" data-item-categories="donations" data-item-max-quantity="1" data-item-taxable=false ) Add to cart
Two things to note here:
Finally, add some frontend code to hold up the donation amount input to the buy button:
// app/static/scripts/donate.js $(function () { document .querySelector('#amount') .addEventListener('change', function (evt) { const amount = evt.target.value let data = $('#donate').data() // Example relies on jQuery data object data.itemPrice = amount data.itemId = `donation` data.itemUrl = `${data.baseUrl}?amount=${amount}` }) });
With that in the correct location, any change made to the #amount field value will update the product URL.
A trend is something that remains with us for a short period of time before fading away. It is a phenomenon that comes and goes.
Now, there is a trending phenomenon which is more obvious in the world of our developers, that in this world of technology, our developers are always in a rush of building new, shining toys, which stays probably forever unlike other trends.
In this part of the article, we will be discussing a trend of our technical world i.e GraphQL.
It is a new form (syntax) of computers that we use for our Application Programming Interface which tells us how we can grab data from single or multiple databases. Everyone must have a thought as to why it has been created? Creating it helped to solve organizational problems.
Now, if we consider facebook’s case, the developers wanted to place all the features of the website into the hands of the users along with their apps, in 2011.
That was the year they build new productive ways. They thought to develop a way that would connect clients and servers, which will be simple but more structured. It made it possible to handle data over a single end of a communication channel through HTTP.
The “type schema system” of it rearranges all the data which you will obtain, despite the fact that has several fields. You can connect one with another to fetch all the information required in one simple request.
Now, here we come to another trend, which is termed as Node.js Express.
It is a fast web framework for one-page, two-page or hybrid web applications . It’s possibly the most popular framework in recent times.
It’s an uncomplicated framework including essential features of web applications on top of NodeJS eCommerce.
There are a lot of elements which we can add up to manage most cases. Still, going with the classic will be the best idea.
We will begin by initializing a new node project.
npm init
Some quick questions which the Command-line interface will ask need to be answered.
This will build the project.json file and then we will now begin the real fight.
Firstly, we require an addition to the Express npm package.
npm install express--save
Secondly, an entry file of our application needs to be created. Let’s give it a name for example, server.js .
After this, we need to set the view engine we will be using. In this case, we will be moving further with pug .
npm install pug--save.
After that, we will be adding these lines to the server.js file.
This will help to arrange our default view engine and the path from where our view will be detected.
Then we will have to create a router to make an appearance of the list of our products. You need to create a new directory app in your root folder and then you need another folder router.
You need to create a router named product.js.
// /app/routers/products.js const express = require('express') const router = express.Router() router.get('/', (req, res) => { })
Then we have to register this router in our app.
We also need to make an addition of these lines to server.js file:
// /server.js const products = require('./app/routers/products') app.use('/', products)
For GraphCMS, You need to have an account there.
Once you log in, you need to create a new project. Here, we named it as an example (store name) demo. After creating the project, choose content by clicking on it, following it with Add Content Model.
Now, we need to describe the fields of the product and add the necessary fields.
Then you can create a few products. After doing that e, you need to find an API endpoint and made eligible for reading.
Then you need to go to the settings option available in the menu and enable Public API access.
Take note of the Simple Endpoint URL in the endpoints place.
Again, we need to get back to the code.
Now, we need to change our product.js router to fetch our items from the Application program interface. Before this, we need to create a small service component which will communicate with the API with the help of Apollo clients.
Install the components which we need from npm.
npm install apollo-client graphql- tag node-fetch url numeral--save
Also, you have to install node-fetch. The reason is, the fetch process that as apollo-client utilizes is not yet available.
URL and numeral package is a future concern and it’s for display purposes.
Also, create a configuration file in the root of our project which contains Application program interface endpoint URL and example (store name) Application program interface key.
You need to create a new directory named services in the app folder. We will make an addition of a new file named products.js in it.
Now, we have a way to fetch our data. We can now recover a list of products with the help of its id.
Let’s begin by arranging our products in one list. We need to open the router file product.js.
After fetching the products from the GQL API, we need to render a view, which we will be creating.
Let’s begin with the views we require by placing together our base layout. Place a file layout.pug in /app/views directory.
Now when we have a layout, we will be generating the view that will make a list of the products.
Make insertion of a new file named index.pug in /app/view/products folder.
Now, this template will provide each product, along with its details and dual buttons: One button to get to the product and another to add it to the cart.
Then, we will have access to the example (store name) API key and two methods in our templates.
Although the eCommerce sector has become much more competitive and aggressive today, we firmly believe that Node.js Development Services can make a great change for sure, without any doubt.
It is one of the finest coding languages that every expert recommends!
Your information is safe with us. eSparkBiz guarantees 100% data security. We don’t use emails for spamming.