Skip to content

Basant1Saini/shoppyglobe-backend

Repository files navigation

ShoppyGlobe E-commerce Backend

🔗 GitHub Repository: https://github.com/Basant1Saini/shoppyglobe-backend

A complete backend API for the ShoppyGlobe e-commerce application built with Node.js, Express.js, and MongoDB. This project includes user authentication, product management, and shopping cart functionality with JWT-based authorization.

shoppyglobe-backend/
├── User.js              # User model
├── Product.js           # Product model  
├── Cart.js              # Cart model
├── authController.js    # Authentication logic
├── productController.js # Product logic
├── cartController.js    # Cart logic
├── authRoutes.js        # Auth endpoints
├── productRoutes.js     # Product endpoints
├── cartRoutes.js        # Cart endpoints
├── auth.js              # JWT middleware
├── server.js            # Main app
├── .env                 # Database config
├── .gitignore
├── package.json
└── README.md

Installation & Setup

Prerequisites

  • Node.js (v14 or higher)
  • No MongoDB installation required! This project uses MongoDB Atlas (cloud database)

Step 1: Clone the Repository

git clone https://github.com/Basant1Saini/shoppyglobe-backend.git
cd shoppyglobe-backend

Step 2: Install Dependencies

npm install

Step 3: Configure Environment Variables

The project is pre-configured with MongoDB Atlas! The .env file is already set up with a cloud database connection.

The .env file already contains:

PORT=3000
MONGODB_URI=mongodb+srv://basant357_db_user:[email protected]/shoppyglobe?retryWrites=true&w=majority
JWT_SECRET=shoppyglobe_secret_key_2024_production
JWT_EXPIRE=7d

✅ That's it! No local MongoDB installation needed.

Note: The MongoDB Atlas database is shared and accessible to everyone who clones this project.

Step 4: Run the Application

Development mode (with auto-reload):

npm run dev

Production mode:

npm start

The server will start on http://localhost:3000

✅ The app will automatically connect to MongoDB Atlas - no local database needed!

API Endpoints

Base URL

http://localhost:3000

Authentication Routes

1. Register User

  • Endpoint: POST /api/auth/register
  • Access: Public
  • Body:
{
  "name": "John Doe",
  "email": "[email protected]",
  "password": "password123"
}
  • Response:
{
  "success": true,
  "message": "User registered successfully",
  "data": {
    "_id": "user_id",
    "name": "John Doe",
    "email": "[email protected]",
    "token": "jwt_token"
  }
}

2. Login User

  • Endpoint: POST /api/auth/login
  • Access: Public
  • Body:
{
  "email": "[email protected]",
  "password": "password123"
}
  • Response:
{
  "success": true,
  "message": "Login successful",
  "data": {
    "_id": "user_id",
    "name": "John Doe",
    "email": "[email protected]",
    "token": "jwt_token"
  }
}

Product Routes

3. Get All Products

  • Endpoint: GET /api/products
  • Access: Public
  • Response:
{
  "success": true,
  "count": 10,
  "data": [
    {
      "_id": "product_id",
      "name": "Product Name",
      "price": 99.99,
      "description": "Product description",
      "stockQuantity": 50,
      "category": "Electronics",
      "imageUrl": "https://example.com/image.jpg"
    }
  ]
}

4. Get Product by ID

  • Endpoint: GET /api/products/:id
  • Access: Public
  • Response:
{
  "success": true,
  "data": {
    "_id": "product_id",
    "name": "Product Name",
    "price": 99.99,
    "description": "Product description",
    "stockQuantity": 50
  }
}

5. Create Product

  • Endpoint: POST /api/products
  • Access: Public (should be admin-only in production)
  • Body:
{
  "name": "New Product",
  "price": 149.99,
  "description": "Amazing product description",
  "stockQuantity": 100,
  "category": "Electronics",
  "imageUrl": "https://example.com/image.jpg"
}

Cart Routes (Protected - Requires Authentication)

Note: All cart routes require JWT token in Authorization header:

Authorization: Bearer <your_jwt_token>

6. Get User Cart

  • Endpoint: GET /api/cart
  • Access: Private
  • Response:
{
  "success": true,
  "data": {
    "_id": "cart_id",
    "user": "user_id",
    "items": [
      {
        "_id": "item_id",
        "product": {
          "_id": "product_id",
          "name": "Product Name",
          "price": 99.99
        },
        "quantity": 2,
        "price": 99.99
      }
    ],
    "totalAmount": 199.98
  }
}

7. Add Product to Cart

  • Endpoint: POST /api/cart
  • Access: Private
  • Body:
{
  "productId": "product_id",
  "quantity": 2
}

8. Update Cart Item Quantity

  • Endpoint: PUT /api/cart/:id
  • Access: Private
  • Params: id - Cart item ID
  • Body:
{
  "quantity": 5
}

9. Remove Item from Cart

  • Endpoint: DELETE /api/cart/:id
  • Access: Private
  • Params: id - Cart item ID

10. Clear Cart

  • Endpoint: DELETE /api/cart
  • Access: Private

🧪 API Testing Documentation

  • ThunderClient (VS Code Extension) - Recommended

Testing Setup

  1. Start the server:

    npm start

    Server runs on: http://localhost:3000

  2. Install ThunderClient (if using VS Code):

    • Open VS Code Extensions (Cmd+Shift+X)
    • Search "Thunder Client"
    • Click Install

📝 Complete API Testing Guide

Step 1: Test Authentication

1.1 Register New User

Request:

POST http://localhost:3000/api/auth/register
Content-Type: application/json

Body:
{
  "name": "Test User",
  "email": "[email protected]",
  "password": "password123"
}

Expected Response (201):

{
  "success": true,
  "message": "User registered successfully",
  "data": {
    "_id": "679...",
    "name": "Test User",
    "email": "[email protected]",
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }
}

✅ COPY THE TOKEN - You'll need it for cart operations!


1.2 Login User

Request:

POST http://localhost:3000/api/auth/login
Content-Type: application/json

Body:
{
  "email": "[email protected]",
  "password": "password123"
}

Expected Response (200):

{
  "success": true,
  "message": "Login successful",
  "data": {
    "_id": "679...",
    "name": "Test User",
    "email": "[email protected]",
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }
}

Step 2: Test Product Routes

2.1 Create Product

Request:

POST http://localhost:3000/api/products
Content-Type: application/json

Body:
{
  "name": "Laptop",
  "price": 999.99,
  "description": "High performance laptop",
  "stockQuantity": 10
}

Expected Response (201):

{
  "success": true,
  "message": "Product created successfully",
  "data": {
    "_id": "679...",
    "name": "Laptop",
    "price": 999.99,
    "description": "High performance laptop",
    "stockQuantity": 10
  }
}

✅ COPY THE PRODUCT ID - You'll need it for cart testing!


2.2 Get All Products

Request:

GET http://localhost:3000/api/products

Expected Response (200):

{
  "success": true,
  "count": 1,
  "data": [
    {
      "_id": "679...",
      "name": "Laptop",
      "price": 999.99,
      "description": "High performance laptop",
      "stockQuantity": 10,
      "createdAt": "2026-01-22T...",
      "updatedAt": "2026-01-22T..."
    }
  ]
}

2.3 Get Product by ID

Request:

GET http://localhost:3000/api/products/679...

Replace 679... with actual product ID

Expected Response (200):

{
  "success": true,
  "data": {
    "_id": "679...",
    "name": "Laptop",
    "price": 999.99,
    "description": "High performance laptop",
    "stockQuantity": 10
  }
}

Step 3: Test Cart Routes (🔒 Protected - Need Token)

IMPORTANT: For all cart routes, add this header:

Authorization: Bearer YOUR_TOKEN_HERE

3.1 Add Product to Cart

Request:

POST http://localhost:3000/api/cart
Content-Type: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Body:
{
  "productId": "679...",
  "quantity": 2
}

Replace productId with actual product ID from Step 2.1

Expected Response (200):

{
  "success": true,
  "message": "Product added to cart successfully",
  "data": {
    "_id": "679...",
    "user": "679...",
    "items": [
      {
        "_id": "679...",
        "product": {
          "_id": "679...",
          "name": "Laptop",
          "price": 999.99
        },
        "quantity": 2,
        "price": 999.99
      }
    ],
    "totalAmount": 1999.98
  }
}

✅ COPY THE ITEM ID (items[0]._id) - You'll need it for update/delete!


3.2 Get Cart

Request:

GET http://localhost:3000/api/cart
Authorization: Bearer YOUR_TOKEN_HERE

Expected Response (200):

{
  "success": true,
  "data": {
    "_id": "679...",
    "user": "679...",
    "items": [
      {
        "_id": "679...",
        "product": { ... },
        "quantity": 2,
        "price": 999.99
      }
    ],
    "totalAmount": 1999.98
  }
}

3.3 Update Cart Item Quantity

Request:

PUT http://localhost:3000/api/cart/679...
Content-Type: application/json
Authorization: Bearer YOUR_TOKEN_HERE

Body:
{
  "quantity": 5
}

Replace 679... with actual cart item ID from Step 3.1

Expected Response (200):

{
  "success": true,
  "message": "Cart item updated successfully",
  "data": {
    "items": [
      {
        "quantity": 5,
        "price": 999.99
      }
    ],
    "totalAmount": 4999.95
  }
}

3.4 Remove Item from Cart

Request:

DELETE http://localhost:3000/api/cart/679...
Authorization: Bearer YOUR_TOKEN_HERE

Replace 679... with actual cart item ID

Expected Response (200):

{
  "success": true,
  "message": "Item removed from cart successfully",
  "data": {
    "items": [],
    "totalAmount": 0
  }
}

Step 4: Test Error Scenarios

4.1 Access Cart Without Token (Should Fail)

Request:

GET http://localhost:3000/api/cart

(No Authorization header)

Expected Response (401):

{
  "success": false,
  "message": "Not authorized, no token provided"
}

4.2 Invalid Login Credentials

Request:

POST http://localhost:3000/api/auth/login
Content-Type: application/json

Body:
{
  "email": "[email protected]",
  "password": "wrongpassword"
}

Expected Response (401):

{
  "success": false,
  "message": "Invalid credentials"
}

4.3 Product Not Found

Request:

GET http://localhost:3000/api/products/invalidid123

Expected Response (500):

{
  "success": false,
  "message": "Error fetching product"
}

💡 Quick Testing Tips

  1. Save your token - Copy it from register/login response
  2. Save product IDs - You'll need them for cart operations
  3. Save cart item IDs - Different from product IDs!
  4. Test in order - Register → Login → Create Product → Add to Cart
  5. Check responses - All successful requests return "success": true

Error Handling

The API includes comprehensive error handling for:

  • ✅ Validation errors (missing or invalid fields)
  • ✅ Authentication errors (invalid/expired tokens)
  • ✅ Authorization errors (unauthorized access)
  • ✅ Database errors (connection, duplicate keys)
  • ✅ Not found errors (invalid IDs, missing resources)
  • ✅ Server errors (500 status codes)

MongoDB Database Structure

Collections

  1. users - User authentication data

    • name, email, password (hashed)
  2. products - Product catalog

    • name, price, description, stockQuantity, category, imageUrl
  3. carts - Shopping carts

    • user reference, items array, totalAmount

Security Features

  • ✅ Password hashing with bcryptjs
  • ✅ JWT token-based authentication
  • ✅ Protected routes with authentication middleware
  • ✅ Input validation on all endpoints
  • ✅ CORS enabled for cross-origin requests
  • ✅ Environment variables for sensitive data

License

ISC

Author

Basant Saini

Contact

For questions or issues, please open an issue on GitHub.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors