Skip to content

renebitter/mernshop

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Mernshop

Fullstack eCommerce - MERN with Redux

https://mernshop-kk1f.onrender.com/

About

Build with React and Redux for it's state management. This is a fully functional e-commerce website including: product listing, pagination, product detail page, search, user authentication, user profile page, rating, review and payment (paypal integration). Admin user and admin area with CRUD functionality for users, products and orders.

Content

Backend

  • server.js

  • config

    • db.js (connects to mongodb)
  • controllers order product user

  • data

    Can be seeded with seeder.js utility (current DB entries will be deleted!)

      "data:import": "node backend/seeder",
      "data:destroy": "node backend/seeder -d",

  • middleware auth error

  • models order product user

  • routes order product user upload

  • utils generateToken seeder

Frontend

  • index.js

    • Provider store={store}
  • App.js

    • Route path='/admin/orderlist' component={OrderListScreen}

State_Management

  • store.js

    • imports { createStore, combineReducers, applyMiddleware } from 'redux'.
    • import thunk from 'redux-thunk';
    • imports { composeWithDevTools } from 'redux-devtools-extension'
    • imports all reducers. Combines them into a single variable "reducer" with Redux's "combineReducers".
    • uses localStorage for cartItems, userInfo, shippingAddress.
    • sets initialState using localStorage info.
    • defines middleware variable with "thunk".
    • creates store with Redux's "createStore" using variables defined previously: reducer, initialState and composeWithDevTools(applyMiddleware(...middleware)).
  • Constants

    • defines variables Cart Product Order User
  • Actions

    • fetches API Cart Product Order User
  • Reducers

    • takes previous state and action, and returns next state Cart Product Order User

Components

  • Footer //
  • CheckoutSteps.js
  • FormContainer
  • Header.js ({userLogin}, { history }, {userInfo})
  • Loader //
  • Message (defaultProps ‘info’)
  • Meta (Helmet)
  • Pagination (Array)
  • Product ({product})
  • ProductCarousel
  • Rating
  • SearchBox

Pages

  • Main: Home Product Cart
  • Auth: Login Register Profile Shipping Payment PlaceOrder Order
  • Admin: OrderList ProductEdit ProductList UserEdit UserList

Dependencies

Backend_Dependencies

  • Production

    • bcryptjs

      • Hashes PW: Enables storing of passwords as hashed passwords instead of plaintext.

        .hashSync synchronously generates a hash for the given string. It returns the hashed string.

        import bcrypt from 'bcryptjs';
        const users = [
          {
            name: 'Walter White',
            email: 'heisenberg@saymyna.me',
            password: bcrypt.hashSync('123456', 10),
          },
        ];
      • Compares PW: .compare asynchronously compares the given data against the given hash.

        userSchema.methods.matchPassword = async function (enteredPassword) {
          return await bcrypt.compare(enteredPassword, this.password);
        };
      • Salts: .genSalt asynchronously generates a salt. A salt randomizes each hash by adding random data that is unique to each user to their password hash, so even the same password has a unique hash.

        .hash asynchronously generates a hash for the given string.

        const salt = await bcrypt.genSalt(10);
        this.password = await bcrypt.hash(this.password, salt);
    • dotenv

      • loads environment variables from a .env file into process.env.

        * seems unnecessary when using a Heroku or alike. You can set the env vars directly in the config var settings from the server itself.

    • express

      • framework for node. Note: "type": "module" in "package.json" allows for import instead of require.
    • express-async-handler

      • middleware for handling exceptions inside of async express routes and passing them to your express error handlers. await/throw new Error

        import asyncHandler from 'express-async-handler';
        
        const updateProduct = asyncHandler(async (req, res) => {
        
          //...
        
          if (product) {
        
            //...
        
              const updatedProduct = await product.save();
              res.json(updatedProduct);
            } else {
              res.status(404);
              throw new Error('Product not found');
          }
        }

    • jsonwebtoken

      • securely transmit info between parties as a JSON object.

        import jwt from 'jsonwebtoken';
        
        const generateToken = (id) => {
          return jwt.sign({ id }, process.env.JWT_SECRET, { expiresIn: '30d' });
        };
        
        //...
        
        const decoded = jwt.verify(token, process.env.JWT_SECRET);

    • mongoose

      • MongoDB object modeling tool.

        import mongoose from 'mongoose';
        
        //...
        
        const conn = await mongoose.connect(process.env.MONGODB_URI, {
          useUnifiedTopology: true,
          useNewUrlParser: true,
          useCreateIndex: true,
        });
          const productSchema = mongoose.Schema(
          {
            user: {
              type: mongoose.Schema.Types.ObjectId,
              required: true,
              ref: 'User',
            },
            name: {
              type: String,
              required: true,
            },
            image: {
              type: String,
              required: true,
            },
        
          }
        
        
          //...
        
          const Product = mongoose.model('Product', productSchema);

    • multer

      • Used for uploading files. "uploadFiles.js"
  • Dev

    • concurrently

      • Run multiple commands concurrently
      "dev": "concurrently \"npm run server \" \"npm run client\"",
    • morgan

      • HTTP request logger middleware for node.js. To be used in conjunction e.g. with Insomnia or Postman.

      Image ...

    • nodemon

      • automatically restarts node application when file changes are detected.
      "scripts": {
        "server": "nodemon backend/server",
      }

Frontend_Dependencies

  • Production
    • axios
    • react
    • react-bootstrap
    • react-dom
    • react-helmet
    • react-paypal-button-v2
    • react-redux
    • react-router-bootstrap
    • react-router-dom
    • react-scripts
    • redux
    • redux-devtools-extension
    • redux-thunk