How I built an E-commerce API with NodeJs, Express and MongoDB(Part 1)
Introduction
Recently, I was fortunate enough to be accepted as an intern at Genesys Tech Hub, Enugu and as part of our development in software engineering we were meant to have a passion project which we would work on alone apart from building a product while working in a team.
I chose to build an E-commerce API and this is how I did it . You can too, if you follow the steps in this tutorial.
Basically this is a simple API. It doesn’t have all the fancy features of a modern E-Commerce web application but it does have all the basic features to get things started. You can surely add more features to make this better.
Prerequisites
- Basic understanding of javascript
- Basic knowledge of Nodejs, MongoDB, Mongoose and Express
The basic features in this API would be:
- Signing Up, signing in and signing out of users
- Authentication using JSON Web Tokens (JWT).
- Option to add, edit, view and delete all products in the store.
- Option to add items or remove items from the cart.
- Create cart for each user, add and remove items from the cart and also calculate the bill.
I will be using Express on NodeJs for the server, MongoDB to store data as document in JSON format and Mongoose for modeling.
Create a new folder, I named mine e-commerce-api, Launch VSCode or your preferred code editor, open the terminal and type the command in the terminal to initiate a new Node project there
npm init
You will be walked through a series of steps to create a package.json file for your project or you could just use the -y
flag is to skip customization and use default values, so this command becomes
npm init -y
Next, we install dependencies.
Dependencies, just like the name suggests are, modules which our project rely on to function as a whole. We’ll be installing quite a number of them, but I’ll first do a run-down on what each does before we install.
- bcryptjs — We’ll be authenticating users in our application. They’ll need passwords to sign in and we’ll be storing this password in our database. It isn’t advisable to store password as plain text as this leaves our application vulnerable so this is where bcrypt comes in. Bcrypt provides us with a password-hashing function which we can use before saving these passwords in our database.
- Express — A node framework for building web applications and APIs
- jsonwebtoken — Generates auth tokens to validate users
- Mongoose — Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.
- validator — a library of string validators. We’ll be using this to validate user emails.
- env-cmd — we’ll use this to load environmental variables from an external file.
- nodemon — It keeps our server running by restarting it anytime changes are detected in our files.
I added a few scripts to make development easier, here are they
- dev — it starts the development server by calling env-cmd to load in environmental variables, then nodemon to start the server.
"dev":"env-cmd -f ./config/dev.env nodemon src/app.js"
I’ll explain later on, what’s going on here. So just bear with me for the moment. - start — this starts our on the production server. This is the command heroku will run while trying to start our application.
"start":”node src/app.js”
This is what my package.json looks like afterwards.
I would suggest you install the same versions of dependences to avoid running into issues along the way.
Now, let's get to building.
- Setting up environmental variables and mongoose
Create a folder named config in your root directory, in this folder create a new file named dev with .env as its extension. This file will hold our environmental variables.
Copy and save this in the file
JWT_SECRET=ecommercewebapi
PORT=3000
MONGODB_URL=mongodb://127.0.0.1:27017
This brings me back to our dev script"dev":"env-cmd -f ./config/dev.env nodemon src/app.js"
The -f
flag is used to specify where our env file is saved on our machine and right after calling nodemon, we specify the path to our server file.
Next up we set up connection with mongoose to our database.
Create a folder named db in your root directory, in this folder create a new file named mongoose with a js extension.
Copy and paste this code in this file
const mongoose = require(‘mongoose’);
mongoose.connect(process.env.MONGODB_URL, {
useNewUrlParser: true,
})
Here, we are loading in mongoose and connecting with the MONGODB URL specified in our env file.
save the file and let’s move on to creating our app.js file.
2. Creating the server
Create a new file in your root directory.
Let’s name that app.js
First we import all dependencies
const express = require(‘express’)
require(‘./db/mongoose’)
We will then call our express app and set it up for use
const app = express()
app.use(express.json())
Next up, we specify the port we want our server to listen on. Remember we’ve defined this in our env file. So,
const port = process.env.PORT
Now it’s time to listen for connectionsapp.listen(port, () => {
console.log(‘server listening on port ‘ + port)
})
Start up mongoDB and also start up the server using npm run dev.
If all goes well, you should see this on your console
This is what our app.js file would look like by the time we’re finished.
This concludes the first part to this tutorial series.
In the next parts, we’ll be dealing with our models, routes and authentication.
Hit this link to jump into the next article where we build out the models