The Talent500 Blog
react

Building a Full Stack E-commerce Application with React, Node.js, Express, and MongoDB for Data Storage

E-commerce has become an essential part of our lives with technology coming to the forefront. With the rise of online shopping, the demand for efficient and robust e-commerce applications has never been greater. In this blog, we will guide you through the process of building a full-stack e-commerce application using popular web technologies: React for the front end, Node.js and Express for the back end, and MongoDB for data storage. By the end of this article, you’ll have a powerful and scalable e-commerce application ready to deploy.

Building a Full Stack E-commerce Application with React, Node.js, Express, and MongoDB for Data Storage 1

Setting Up the Environment

Before we delve into coding, it’s essential to ensure that we have the necessary tools and software installed. Make sure you have Node.js and npm (Node Package Manager) installed on your machine, as well as MongoDB to set up our database. With these prerequisites in place, we can move forward.

Front-end Development with React

Building a Full Stack E-commerce Application with React, Node.js, Express, and MongoDB for Data Storage 2

Let us start by creating the front end of our e-commerce application using React. React is a popular JavaScript library for building user interfaces, and it provides a smooth and efficient way to develop interactive web applications.

To create a new React application, open your terminal or command prompt and run the following commands:

bash

npx create-react-app e-commerce-app

cd e-commerce-app

Next, let’s set up the project structure and add some essential components. Create a “components” folder inside the “src” directory to organize our React components.

javascript

// src/components/Header.js

import React from ‘react’;

const Header = () => {

  return (

    <header>

      <h1>E-Commerce App</h1>

      {/* Add navigation and other components as needed */}

    </header>

  );

};

 

export default Header;

The Header component will represent the top part of our application, displaying the title and any navigation elements we may add later.

javascript

// src/App.js

import React from ‘react’;

import Header from ‘./components/Header’;

 

function App() {

  return (

    <div className=”App”>

      <Header />

      {/* Add other components and pages here */}

    </div>

  );

}

 

export default App;

In the App component, we have imported the Header component and used it to render the application’s header.

Back-end Development with Node.js and Express

Building a Full Stack E-commerce Application with React, Node.js, Express, and MongoDB for Data Storage 3

With our front-end set-up, let’s create the back-end using Node.js and Express. Node.js is a server-side JavaScript runtime that allows us to build scalable and performant web applications. Express is a popular web application framework for Node.js that simplifies the process of building web servers.

To set up the back end, open a new terminal or command prompt, create a new directory for the back end, and initialize a new Node.js project. Then, install the necessary dependencies:

bash

mkdir backend

cd backend

npm init -y

npm install express mongoose cors body-parser

With our back-end dependencies installed, let’s set up the Express server and connect it to our MongoDB database.

javascript

// backend/server.js

const express = require(‘express’);

const mongoose = require(‘mongoose’);

const cors = require(‘cors’);

const bodyParser = require(‘body-parser’);

 

const app = express();

const port = process.env.PORT || 5000;

 

app.use(cors());

app.use(bodyParser.json());

 

});const connection = mongoose.connection;

connection.once(‘open’, () => {

  console.log(‘MongoDB database connection established successfully’);

});

// Define your routes and controllers here

 

app.listen(port, () => {

  console.log(`Server is running on port: ${port}`);

});

In this code, we have imported the required packages, set up the Express app, and connected it to our MongoDB database. We have also configured the server to listen on a specified port.

Creating Models and Controllers

Building a Full Stack E-commerce Application with React, Node.js, Express, and MongoDB for Data Storage 4

With the server set up, let’s define the models and controllers for our e-commerce application. Models in the context of MongoDB are used to define the structure of our data, while controllers handle the logic for processing requests and returning responses.

For simplicity, let’s create a basic model for our products. Products will be the main entities in our e-commerce application.

javascript

// backend/models/product.model.js

const mongoose = require(‘mongoose’);

const Schema = mongoose.Schema;

 

const productSchema = new Schema(

  {

    name: { type: String, required: true },

    description: { type: String, required: true },

    price: { type: Number, required: true },

    // Add more product fields as needed

  },

  {

    timestamps: true,

  }

);

const Product = mongoose.model(‘Product’, productSchema);

module.exports = Product;

In this code, we have defined a product schema using Mongoose, which includes fields such as name, description, and price. The “timestamps” option will automatically add “createdAt” and “updatedAt” fields to our documents.

Next, let’s create the controller for our products, where we can handle CRUD (Create, Read, Update, Delete) operations.

javascript

// backend/controllers/product.controller.js

 

const Product = require(‘../models/product.model’);

 

// Get all products

const getAllProducts = async (req, res) => {

  try {

    const products = await Product.find();

    res.json(products);

  } catch (err) {

    res.status(500).json({ error: err.message });

  }

};

 

// Add a new product

const addProduct = async (req, res) => {

  const { name, description, price } = req.body;

 

  const newProduct = new Product({ name, description, price });

 

  try {

    await newProduct.save();

    res.json(‘Product added successfully’);

  } catch (err) {

    res.status(400).json({ error: err.message });

  }

};

 

// Implement update and delete operations as needed

 

module.exports = {

  getAllProducts,

  addProduct,

};

In this controller, we have defined two functions: getAllProducts and addProduct. The getAllProducts function fetches all products from the database and returns them as a JSON response. The addProduct function creates a new product document in the database based on the data received in the request body.

Integrating the Front-end and Back-end

Building a Full Stack E-commerce Application with React, Node.js, Express, and MongoDB for Data Storage 5

Now that we have our front-end and back-end set up, let’s integrate them to create a fully functional e-commerce application.

javascript

// frontend/src/App.js

 

import React, { useState, useEffect } from ‘react’;

import axios from ‘axios’;

 

function App() {

  const [products, setProducts] = useState([]);

 

  useEffect(() => {

    axios.get(‘http://localhost:5000/products’).then((response) => {

      setProducts(response.data);

    });

  }, []);

 

  return (

    <div className=”App”>

      <Header />

      <main>

        <h2>Products</h2>

        <ul>

          {products.map((product) => (

            <li key={product._id}>

              <h3>{product.name}</h3>

              <p>{product.description}</p>

              <p>${product.price}</p>

            </li>

          ))}

        </ul>

      </main>

    </div>

  );

}

 

export default App;

In the App component, we have imported React’s useState and useEffect hooks to manage the state of our products. We use the useEffect hook to make an HTTP GET request to our back-end API and fetch all products from the database. The products are then displayed in the application’s main section using the map function.

Building a Full Stack E-commerce Application with React, Node.js, Express, and MongoDB for Data Storage 1

Conclusion

In this blog, we have successfully built a full-stack e-commerce application using React for the front end, Node.js and Express for the back end, and MongoDB for data storage. We covered setting up the environment, creating models and controllers, and integrating the front end with the back end. This is just the beginning, and there are countless possibilities to expand and enhance this application.

You can add features like user authentication, shopping cart functionality, or payment gateways to make your e-commerce application even more powerful and user-friendly. Additionally, consider implementing search and filtering options, user reviews, and product ratings to provide a seamless shopping experience.

Remember to keep exploring and stay curious about coding. By combining the power of React, Node.js, Express, and MongoDB, you’ve unlocked the potential to build scalable and feature-rich applications that can adapt to the ever-changing world of e-commerce. 

0
Afreen Khalfe

Afreen Khalfe

A professional writer and graphic design expert. She loves writing about technology trends, web development, coding, and much more. A strong lady who loves to sit around nature and hear nature’s sound.

Add comment