Building an E-Commerce Application with MEAN

4.4 (8 reviews total)
By Adrian Mejia
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Getting Started with the MEAN Stack

About this book

MEAN stands for MongoDB, Express, AngularJS, and Node.js. It is a combination of a NoSQL database, MongoDB, with a couple of JavaScript web application frameworks, namely Express.js and Angular.js. These run on Node.js.

There is always an ever-growing list of requirements while designing an e-commerce application, which needs to be flexible enough for easy adaptation. The MEAN stack allows you to meet those requirements on time and build responsive applications using JavaScript.

This book will show you how to create your own e-commerce application using the MEAN stack. It will take you step by step through the parallel process of learning and building. It will also teach you to develop a production-ready, high-quality e-commerce site from scratch and will provide the knowledge you need to extend your own features to the e-commerce site.

This book starts with a short introduction to the MEAN stack, followed by a step-by-step guide on how to build a store with AngularJS, set up a database with MongoDB, create a REST API, and wire AngularJS. It also shows you how to manage user authentication and authorization, check multiple payment platforms, add products’ search and navigation, deploy a production-ready e-commerce site, and finally add your own high-quality feature to the site.

By the end of the book, you will be able to build and use your own e-commerce app in the real world and will also be able to add your own new features to it.

Publication date:
November 2015


Chapter 1. Getting Started with the MEAN Stack

In order to build a powerful and interactive e-commerce application, business logic has to move closer to the users, also known as thick clients. JavaScript is well-suited for this job since it is the native language of the web. Any browser on any device can support it without any plugins. Furthermore, we can dramatically increase the interactivity and speed of a web application using JavaScript and HTML5. Instead of rendering the whole web page every time the user clicks something (as with the traditional server side languages), we can use asynchronous calls to quickly fetch data from the server and render only what's required.

The MEAN stack (MongoDB, ExpressJS, AngularJS, and NodeJS), as you might already know, is a JavaScript full stack web development framework. Using only one main programming language from the client side all the way back to the server and the database has many advantages, as we are going to discuss later.

Some companies like Wallmart, Groupon, Netflix, and PayPal have moved from traditional enterprise web frameworks (like Java's Spring MVC and Ruby on Rails) to NodeJS and thick JavaScript clients. This improved not just their productivity but also their performance! They have reported an increase in the requests per second as well as a decrease in their development time.

I hope you are as excited as I am to build an e-commerce app using state-of-the-art technology like the MEAN stack with the help of this book. By the end of this book, you will not only know more about MEAN e-commerce apps but also about following the best practices. You will get familiar with concepts like Agile methodologies, sprint/iterations, continuous integration, Test Driven Development (TDD), and production deployment.

We are going to cover some ground in this first chapter, and then deepen our knowledge on each of the MEAN stack components. The topics that will be covered in this chapter are as follows:

  • Installing the MEAN components

  • Understanding the project structure

  • Previewing the final app built-in this book

  • Understanding the requirements for e-commerce applications


Introducing the MEAN stack

MEAN is more than an acronym; it offers the following advantages over its traditional alternatives such as LAMP (Linux, Apache, MySQL, and PHP) and other solution stacks:

  • Asynchronous programming (evented non-blocking I/O) which is translated into high throughput and scalability

  • One single programming language across the whole project which is translated into fast paced development and is easy to learn

  • Vibrant community. NPM packages have grown faster than any other programming language community yet

  • Excellent for JSON APIs, Single-Page Applications (SPAs), and soft real-time applications

As for any other solution, there are some disadvantages as well, but they can be mitigated as follows:

  • CPU/thread-intensive apps: Applications that have to deal with heavy CPU usage and low I/O are not very well suited for NodeJS. Some examples of such applications are video encoding and artificial intelligence, which are probably better handled in C/C++. NodeJS supports C++ add-ons, so seamless integrations are an option.

In general, this is how SPAs (and the MEAN stack) work: when a client request is received from the user's browser, it hits the ExpressJS web server first. ExpressJS runs on top of the NodeJS platform, and it connects to the MongoDB database as needed. Finally, the client's request is answered with an AngularJS application. From that point on, all subsequent requests are made behind the scenes through AJAX to the ExpressJS API. AngularJS takes care of rendering any new data instantly and avoiding unnecessary full-page refreshes.

Figure 1: MEAN stack components

Now, let's go through each component individually.


NodeJS is a platform that allows running of the JavaScript code outside of the browser. It's built on top of Google Chrome's V8 JavaScript runtime environment. Thanks to its non-blocking I/O and event-driven model, it is very fast and uses each CPU cycle optimally.

The JavaScript event-loop is sometimes confusing for developers who are new to JavaScript. In many popular languages (Java, Ruby, Python), each thread executes only one line of code at a time (everything else is blocked). However, JavaScript was conceived to be responsive at all times, so it makes heavy use of callbacks and the event-loop. The event-loop is an internal loop that executes all the code, and does not wait for anything in particular. The callbacks are called when a process is done. For instance, for blocking the I/O, a database query will make the thread sit and wait for the result. On the other hand, in JavaScript, it will continue executing the successive lines of code. When the database result is ready, it will be handled by the callback. Thus, non-blocking I/O.

NodeJS will be our server-side platform, and we will need it to run our web server, ExpressJS.


ExpressJS is a web framework for NodeJS. It is a very transparent webserver that not only allows us to build web applications but also to expose RESTful JSON APIs. Express is very modular, so we can process/modify any requests using something called middleware. There are middlewares to provide authentication, handling cookies, logging, error handling and other such functions.


MongoDB is an open source document-oriented database, one of the most popular in the NoSQL database world. It favors a JSON-like document structure rather than the more traditional table-based structures found in relational databases. Its query language is very powerful and expressive. Later in this book, we are going to compare the equivalent SQL queries to MongoDB queries.

MongoDB stores all the users' data, products, orders, and anything that needs to be persistent in the e-commerce application.


AngularJS is an open source JavaScript MVC framework (it might also be referred to as MV* or MVW[Whatever]). This framework enhances the HTML markups with new directives, properties, and tags, and always keeps the views and models in sync. AngularJS facilitates the creation of data-driven and Single-Page Applications (SPAs).


Installing the MEAN component

All right. Enough theory, let's get our hands dirty and execute some command lines.

Installing NodeJS

The node community has been very busy lately and has created more packages for it than any other existing platform. Not just packages but the core development too has been forked (for example, ioJS) and merged back to the main line. Since we are aiming for production, we are going with the current stable version v0.12. We are going to use NVM (Node Version Manager) to switch easily between versions when newer versions become stable.


If you are a Windows user, you can see the instruction on the NVM site at

For most *nix users, this is how you install NVM:

$ curl | bash
$ source ~/.nvm/
$ nvm install 0.12
$ nvm use 0.12

The NodeJS installation comes with the NPM (Node Package Manager). You can verify if node and npm were installed correctly by checking the versions, as follows:

$ node -v
# v0.12.7

$ npm -v
# 2.11.3


In case you have multiple versions of NodeJS, you might want to set v0.12 as the default. So when you open a new terminal and it has the right version, use the nvm alias default 0.12 command to do so.

Installing ExpressJS

You can download Express using npm by typing the following in your terminal:

npm install -g [email protected]

Note that we are downloading a specific version using @4.13.3; the -g argument means that we are installing the package globally.

Installing MongoDB

If you are using a Mac, I'd recommend installing brew first:

ruby -e "$(curl -fsSL"

Then you can install MongoDB:

brew update && brew install mongodb 3.0.2


sudo apt-get -y install mongodb=3.0.2


For other operating systems, follow the instructions given at the official site at

Installing AngularJS tools

You don't need to install the AngularJS tools like the other components so far. We can just download the Angular JavaScript files from its website at and source it in our HTML. The other option is to source it directly from a Content Delivery Network (CDN). However, if you notice, every time you start a new web app, you have to execute the same steps over and over again, for example, type HTML5 doctype, copy initial code, create the directory structure, and so on. All this boilerplate can be automated using a tool called Yeoman. There are many generators in the Yeoman repository. They can scaffold most of the JavaScript frameworks out there: AngularJS, BackboneJS, and the like; if it doesn't exist, you can also create your own. The best ones that suit our needs are angular-fullstack and meanjs. We are going to use the first one since it provides out-of-the-box functionality that is closer to our needs. Let's go ahead and install it:

# Install all the tools
$ npm install -g [email protected]

# Make a new directory 'meanshop'
$ mkdir meanshop && cd $_

# Execute the AngularJS scaffold
$ yo angular-fullstack meanshop


You will see a lot of things going on when you run the commands. But don't worry, we are going to explain all the magic in the next few chapters. For now, play along and get everything installed.

The command line has some kind of wizard that asks you about your preferences. The following are the ones that we are going to use throughout the examples in this book:

# Client

? What would you like to write scripts with? JavaScript + Babel
? What would you like to write markup with? HTML
? What would you like to write stylesheets with? Sass
? What Angular router would you like to use? uiRouter
? Would you like to include Bootstrap? Yes
? Would you like to include UI Bootstrap? Yes

# Server

? What would you like to use for data modeling? Mongoose (MongoDB)
? Would you scaffold out an authentication boilerplate? Yes
? Would you like to include additional oAuth strategies? Google, Facebook, Twitter
? Would you like to use Yes

# Project

? What would you like to write tests with? Mocha + Chai + Sinon
? What would you like to write Chai assertions with? Expect

It takes a while, because it installs a number of packages for you. Take a look into package.json and bower.json. Bower is another package manager like npm but for the frontend libraries. After the installation is complete, you can run the example app with these commands:

# Build
$ grunt

# Preview the app in development mode
$ grunt serve

# Preview the app in production mode
$ grunt serve:dist


You can preview the scaffolded app at: http://localhost:9000. If you get errors, remember that you need to have mongod running.

The AngularJS debugger

Most of the modern browsers provide debugging tools for JavaScript. There's a Google Chrome plugin called Batarang, which is a web inspector extension. I'd recommend getting it installed since it adds more context and useful information and hints:

Example of the output of Batarang AngularJS extension for Chrome's web inspector.


You can find more information about Batarang at


Understanding the project structure

Applications built with the angular-fullstack generator have many files and directories. Some code goes into the client, some executes in the backend, and another portion is just needed for development, such as the tests suites. It's important to understand the layout to keep the code organized.

Yeoman generators are time savers. They are created and maintained by the community following the current best practices. It creates many directories and a lot of boilerplate code to get you started. It might be a bit overwhelming at first to see the number of (possibly) unknown files there. Do not panic, we are going to cover them here and in the next few chapters.

Review the directory structure that was created. There are three main directories: client, e2e, and server:

  • The client folder contains the AngularJS files and assets

  • The server directory contains the NodeJS files, which handle ExpressJS and MongoDB

  • Finally, the e2e files contain the AngularJS end-to-end tests

The file structure

The following is an overview of the file structure of this project:

├── client
│   ├── app        - App specific components
│   ├── assets     - Custom assets: fonts, images, etc…
│   └── components - Non-app specific/reusable components

├── e2e            - Protractor end to end tests

└── server
    ├── api        - Apps server API
    ├── auth       - Authentication handlers
    ├── components - App-wide/reusable components
    ├── config     - App configuration
    │   └── local.env.js - Environment variables
    │   └── environment  - Node environment configuration
    └── views            - Server rendered views

Zooming into clients/app, we will find that each folder has the name of the component (main page, products page), and that inside each folder are all the files related to that component. For instance, if we look inside main, we will find the AngularJS files, CSS (scss), and HTML:

├── main.js                 - Routes
├── main.controller.js      - Controller
├── main.controller.spec.js - Test
├── main.html               - View
└── main.scss               - Styles

Similarly, for our back-end, we have folders named after the components with all the related files inside. We will find NodeJS files, ExpressJS routes, SocketIO events, and mocha tests:

├── index.js                - Routes
├── thing.controller.js     - Controller
├── thing.model.js          - Database model
├── thing.socket.js         - Socket events
└── thing.spec.js           - Test


There are a number of tools used in this project that you might be already familiar with. If that's not the case, read the brief description given, and when needed. we will describe it more thoroughly.


AngularJS comes with a default test runner called Karma, and we are going to leverage its default choices:

  • Karma: This is the JavaScript unit test runner.

  • Jasmine: This is the BDD framework for testing the JavaScript code, which is executed with Karma.

  • Protractor: This is used for end-to-end tests with AngularJS. This is the highest level of testing, which runs in the browser and simulates user interactions with the app.


The following are some tools/libraries that we are going to use for increasing our productivity:

  • GruntJS: This tool serves to automate repetitive tasks such as CSS/JS minification, compilation, unit testing, and JS linting.

  • Yeoman (yo): This is a CLI tool for scaffolding web projects. It automates the creation of directories and files through generators, and also provides command lines for common tasks.

  • Travis CI: This is a Continuous Integration (CI) tool that runs your tests suite every time you commit to the repository.

  • EditorConfig: This is an IDE plugin, which loads the configuration from a file, .editorconfig. For example, you can set indent_size = 2, indents with spaces or tabs, and so on. It's a time saver and maintains consistency across multiple IDEs/teams.

  • SocketIO: This is a library that enables real-time bidirectional communication between the server and the client.

  • Bootstrap: This is a frontend framework for web development. We are going to use it for building the theme throughout this project.

  • AngularJS full-stack: This is the generator for Yeoman that will provide useful command lines to quickly generate server/client code and deploy to Heroku or OpenShift.

  • BabelJS: This is the js-tojs compiler that allows the use of features from the next generation JavaScript (ECMAScript 6) instantly, without waiting for browser support.

  • Git: This is a distributed code versioning control system.

Package managers

AngularJS comes with package managers for third-party backend and frontend modules:

  • NPM: This is the default package manager for NodeJS.

  • Bower: This is the frontend package manager that can be used to handle versions and dependencies of the libraries and assets used in a web project. The file bower.json contains the packages and versions to install, and the file .bowerrc contains the path for the location where those packages need to be installed. The default directory is ./bower_components.

Bower packages

If you have followed the exact steps for scaffolding our app, you will have the following frontend components installed:

  • angular

  • angular-cookies

  • angular-mocks

  • angular-resource

  • angular-sanitize

  • angular-scenario

  • angular-ui-router

  • angular-socket-io

  • angular-bootstrap

  • bootstrap

  • es5-shim

  • font-awesome

  • json3

  • jquery

  • lodash

In the next chapter, we will dive deeper into AngularJS and our file structure. The second part of this chapter is about the functionality of our final app.


Previewing the final e-commerce app

Let's take a break from the terminal. In any project, before starting coding, we need to spend some time planning and visualizing what we are aiming for. That's exactly what we are going to do: draw some wireframes that walk us through the app. Our e-commerce app–MEANshop–will have three main sections:

  • Homepage

  • Marketplace

  • Backoffice


The homepage will contain the featured products, navigation, menus, and some basic information, as you can see in the following image:

Figure 2: Wireframe of the homepage


This section will show all the products, categories, and search results:

Figure 3: Wireframe of the products page


You need to be a registered user for accessing the back office section.

Figure 4: Wireframe of the login page

After you log in, the app will present you with different options depending on your role. If you are the seller, you can create new products, as shown in the following image:

Figure 5: Wireframe of the Product creation page

If you are an admin, you can do everything that a seller does (create products), and you can manage all the users and delete/edit products.


Understanding the requirements for e-commerce applications

There's no better way to learn new concepts and technologies than developing something useful with it. This is why we are building a realtime e-commerce application from scratch. However, there are many kinds of e-commerce apps. In the next section, we are going to delimit what we are going to do.

Minimum Viable Product for an e-commerce site

Even the largest applications that we see today started small and built their way up. The Minimum Viable Product (MVP) is the strict minimum that an application needs to work. In the e-commerce example, it will be the following:

  • Add products with their title, price, description, photo, and quantity

  • Guest checkout page for products

  • One payment integration (for example, PayPal)

This is the minimum requirement for getting an e-commerce site working. We are going to start with these, but by no means will we stop there. We will keep adding features as we go, and build a framework that will allow us to extend the functionality along with high quality.

Defining the requirements

We are going to capture our requirements for the e-commerce application with user stories. A user story is a brief description of a feature told from the perspective of a user, where he expresses his desire and benefit in the following format:

As a <role>, I want <desire> [so that <benefit>]


User stories and many other concepts were introduced with the Agile Manifesto. Learn more about this concept at

The following are the features, captured as user stories, that we are planning to develop through this book:

  • As a seller, I want to create products.

  • As a user, I want to see all the published products and their details when I click on them.

  • As a user, I want to search for a product so that I can find what I'm looking for quickly.

  • As a user, I want to have a category navigation menu so that I can narrow down the search results.

  • As a user, I want to have realtime information so that I can know immediately if a product just got sold out or became available.

  • As a user, I want to check out products as a guest user so that I can quickly purchase an item without registering.

  • As a user, I want to create an account so that I can save my shipping addresses, see my purchase history, and sell products.

  • As an admin, I want to manage user roles so that I can create new admins, sellers, and remove seller permissions.

  • As an admin, I want to manage all the products so that I can ban them if they are not appropriate.

  • As an admin, I want to see a summary of the activities and order statuses.

All these stories might seem verbose, but they are useful for capturing the requirements in a consistent way. They are also handy for developing test cases.


Learn more about user stories at

The technical requirements about deployment, scalability, and performance will be discussed in the final chapters.



In this chapter, we discussed the reasons for using the MEAN stack to build our e-commerce application, and got it installed. This is not just some kind of trend which some companies are migrating to. It gives a tremendous performance boost to the apps, and eases the learning curve using one main language for both, the frontend and the backend. We also described the file structure that we are going to use for organizing the code. Finally, we explored the features that the final app will have, and the way it's going to look and behave. In the next series of chapters, we are going to work with each piece of the MEAN stack individually. Later, we will start integrating all the components and make them work together. The next chapter will cover the most visible part: building the marketplace with AngularJS.

About the Author

  • Adrian Mejia

    Adrian Mejia is a software engineer, full stack web developer, writer, and blogger. He has worked for more than 6 years in the fields of web development and software engineering. He has worked on a variety of projects and platforms, ranging from start-ups to enterprises and from embedded systems to web and e-commerce applications.

    Adrian loves contributing to open source web-related projects and blogging at He started his blog as a reminder to himself of how to solve certain software- and programming-related problems. Later, Adrian noticed that many people found it useful as well, and his blog now gets around 75,000 pageviews every month.

    He holds a master's degree in software engineering from Rochester Institute of Technology (RIT) in Rochester, New York. Adrian has worked at ADTRAN, Inc. as a software engineer since 2012.

    Browse publications by this author

Latest Reviews

(8 reviews total)
The book is outdated and incomplete.
use unix, use node.js version 6.3.1 as last stable release
Excellent and very practical book if you want to build an eCommerce Store with MEAN Stack. .
Book Title
Unlock this book and the full library for FREE
Start free trial