Skip to content

codedpool/primetrade

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ† PrimeTrade - Production-Ready Full Stack REST API

A scalable, secure, and feature-rich full-stack application demonstrating professional-grade backend development with JWT authentication, role-based access control, and comprehensive CRUD operations.

License Node MongoDB Redis Next.js React


πŸ“– Table of Contents


🎯 Overview

PrimeTrade is a production-ready full-stack REST API application designed to demonstrate best practices in backend development. It features:

  • Secure Authentication: JWT-based with refresh token rotation and httpOnly cookies
  • Role-Based Access Control: User and Admin roles with proper authorization
  • Multi-entity Management: Tasks and Notes with full CRUD operations
  • High-Performance Caching: Redis integration for optimized queries
  • Comprehensive Documentation: Swagger UI with interactive API exploration
  • Modern Frontend: Next.js 16 with React 19 and Tailwind CSS
  • Production Deployment: Docker Compose for containerized deployment

Perfect for: Portfolio projects, learning full-stack development, or as a boilerplate for custom applications.


πŸš€ Features

πŸ” Backend (Node.js + Express)

  • βœ… User Authentication

    • Registration with email validation
    • Login with password hashing (bcrypt)
    • JWT access tokens (15-minute expiry)
    • Refresh token rotation (7-day expiry)
    • Secure httpOnly cookie storage
  • βœ… Authorization & Security

    • Role-based access control (user vs admin)
    • Route protection middleware
    • Input validation and sanitization
    • MongoDB injection prevention
    • XSS protection
    • Security headers (Helmet.js)
  • βœ… CRUD Operations

    • Tasks: Create, Read, Update, Delete with status/priority/due dates
    • Notes: Create, Read, Update, Delete with tags and public/private visibility
    • Filtering, searching, and pagination support
    • User-scoped data isolation
  • βœ… Performance & Reliability

    • Redis caching layer for frequently accessed data
    • Rate limiting on auth endpoints (prevents brute force)
    • Comprehensive error handling
    • Graceful error responses with proper HTTP status codes
  • βœ… Developer Experience

    • Swagger UI API documentation
    • Postman collection included
    • Jest test suite with auth tests
    • Detailed logging and debugging support

🎨 Frontend (Next.js + React)

  • βœ… Authentication Pages

    • Beautiful login/register forms
    • Form validation and error display
    • JWT token management with secure storage
    • Auto-redirect to dashboard when authenticated
  • βœ… Protected Dashboard

    • Dashboard overview with statistics
    • Task count and status breakdown
    • Note count display
    • Manual refresh button
  • βœ… Task Management

    • Create, read, update, delete tasks
    • Filter by status (pending, in-progress, completed)
    • Filter by priority (low, medium, high)
    • Search functionality
    • Real-time UI updates
  • βœ… Note Management

    • Create, read, update, delete notes
    • Tag-based organization
    • Public/private visibility toggle
    • Tag filtering support
  • βœ… Admin Panel

    • User management interface
    • View all registered users
    • Change user roles
    • Delete users
  • βœ… User Experience

    • Responsive design (mobile, tablet, desktop)
    • Toast notifications for feedback
    • Loading states and spinners
    • Error messages with action hints
    • Protected routes with auto-redirect

🐳 Deployment

  • βœ… Multi-container Docker Compose setup
  • βœ… MongoDB containerization
  • βœ… Redis containerization
  • βœ… Networking between containers
  • βœ… Environment-based configuration
  • βœ… Production-ready settings

πŸ›  Tech Stack

Backend

Component Technology Version
Runtime Node.js 18+
Framework Express.js 4.21+
Database MongoDB 7+
ODM Mongoose 9.3+
Cache Redis Latest
Client ioredis 5.10+
Authentication JWT jsonwebtoken 9.0+
Password Hashing bcrypt 6.0+
Validation express-validator 7.3+
Security Helmet 8.1+
Documentation Swagger UI 5.0+
Testing Jest 29.7+

Frontend

Component Technology Version
Framework Next.js 16.2+
Library React 19.2+
Styling Tailwind CSS 4+
HTTP Client Fetch API Native
Notifications react-hot-toast 2.6+
Linter ESLint 9+

πŸ— Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    PrimeTrade Application                β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                            β”‚
          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β”‚                 β”‚                 β”‚
    β”Œβ”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”
    β”‚  Frontend   β”‚   β”‚   Backend    β”‚  β”‚   Database  β”‚
    β”‚ (Next.js)   β”‚   β”‚ (Express.js) β”‚  β”‚  (MongoDB)  β”‚
    β”‚ Port: 3000  β”‚   β”‚ Port: 5000   β”‚  β”‚ Port: 27017 β”‚
    β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
          β”‚                 β”‚
          β”‚       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β”‚       β”‚  API (REST)        β”‚
          β”‚       β”‚  /api/v1/*         β”‚
          β”‚       β”‚  Auth, Tasks,      β”‚
          β”‚       β”‚  Notes, Users      β”‚
          β””β”€β”€β”€β”€β”€β”€β–Ίβ””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                           β”‚
                    β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚  Cache Layer    β”‚
                    β”‚  (Redis)        β”‚
                    β”‚  Port: 6379     β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“‹ Prerequisites

Before you begin, ensure you have the following installed:

Verify Installation

node --version    # Should be v18+
npm --version     # Should be 9+

πŸš€ Quick Start

Option 1: Docker Compose (Recommended - Easiest)

Docker Compose automatically sets up MongoDB, Redis, Backend, and Frontend with proper networking.

  1. Clone the repository
git clone <repository-url>
cd primetrade
  1. Create environment file
# Copy the example env file
cp server/.env.example server/.env
  1. Start all services
docker-compose up -d
  1. Verify all services are running
docker-compose ps
  1. Access the application
  1. Stop all services
docker-compose down
  1. View logs
docker-compose logs -f backend    # Backend logs
docker-compose logs -f frontend   # Frontend logs
docker-compose logs -f mongodb    # MongoDB logs
docker-compose logs -f redis      # Redis logs

Option 2: Manual Setup (Development)

If you prefer to run services locally without Docker:

Step 1: Install MongoDB

Linux/Mac:

brew install mongodb-community
brew services start mongodb-community

Windows: Download from MongoDB

Verify:

mongosh  # Should connect to MongoDB shell

Step 2: Install Redis

Linux:

sudo apt-get install redis-server
redis-server

Mac:

brew install redis
brew services start redis

Windows: Use Windows Subsystem for Linux (WSL) or Redis for Windows

Verify:

redis-cli ping  # Should return PONG

Step 3: Backend Setup

cd server

# Install dependencies
npm install

# Create .env file
cp .env.example .env

# Run in development mode
npm run dev

# Or run in production mode
npm start

The backend will start at http://localhost:5000

Step 4: Frontend Setup

Open a new terminal:

cd client

# Install dependencies
npm install

# Create .env.local file
echo "NEXT_PUBLIC_API_URL=http://localhost:5000/api/v1" > .env.local

# Run in development mode
npm run dev

The frontend will start at http://localhost:3000


πŸ”§ Environment Setup

Backend Environment Variables

Create server/.env file with the following variables:

# ================================
# Environment Configuration
# ================================
NODE_ENV=development
PORT=5000

# ================================
# Database Configuration
# ================================
# For local development:
MONGODB_URI=mongodb://localhost:27017/primetrade

# For MongoDB Atlas (cloud):
# MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/primetrade

# For Docker deployment:
# MONGODB_URI=mongodb://mongodb:27017/primetrade

# ================================
# Redis Configuration
# ================================
# For local development:
REDIS_URL=redis://localhost:6379

# For Redis Cloud:
# REDIS_URL=redis://default:password@host:port

# For Docker deployment:
# REDIS_URL=redis://redis:6379

# ================================
# JWT Authentication
# ================================
# Access Token Secret (use a strong, random string in production)
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
JWT_EXPIRE=15m

# Refresh Token Secret (use a different strong string)
JWT_REFRESH_SECRET=your-super-secret-refresh-key-change-this-in-production
JWT_REFRESH_EXPIRE=7d

# ================================
# CORS Configuration
# ================================
# Frontend URL for CORS
FRONTEND_URL=http://localhost:3000

# ================================
# Recommended Production Values
# ================================
# NODE_ENV=production
# JWT_SECRET=<use-strong-random-string>
# JWT_REFRESH_SECRET=<use-different-strong-random-string>
# MONGODB_URI=<use-production-db>
# REDIS_URL=<use-production-redis>

Frontend Environment Variables

Create client/.env.local file:

# Backend API URL for frontend requests
NEXT_PUBLIC_API_URL=http://localhost:5000/api/v1

# For production:
# NEXT_PUBLIC_API_URL=https://api.yourdomain.com/api/v1

Generate Secure Secrets

Use these commands to generate strong random values for JWT secrets:

# Generate a 32-character random string
node -e "console.log(require('crypto').randomBytes(16).toString('hex'))"

# Or use OpenSSL
openssl rand -hex 16

πŸ“ Project Structure

primetrade/
β”‚
β”œβ”€β”€ πŸ“„ docker-compose.yml          # Multi-container orchestration
β”œβ”€β”€ πŸ“„ README.md                   # This file
β”œβ”€β”€ πŸ“„ SCALABILITY.md              # Scalability documentation
β”œβ”€β”€ πŸ“„ Assignment.md               # Project assignment details
β”‚
β”œβ”€β”€ πŸ“‚ server/                     # Backend Node.js/Express
β”‚   β”œβ”€β”€ πŸ“„ package.json
β”‚   β”œβ”€β”€ πŸ“„ jest.config.js
β”‚   β”œβ”€β”€ πŸ“„ .env.example            # Environment variables template
β”‚   β”œβ”€β”€ πŸ“„ Dockerfile
β”‚   β”œβ”€β”€ πŸ“„ README.md               # Backend documentation
β”‚   β”‚
β”‚   β”œβ”€β”€ πŸ“‚ src/
β”‚   β”‚   β”œβ”€β”€ πŸ“„ app.js              # Express app initialization
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ“‚ config/             # Configuration files
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ index.js        # Environment config
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ database.js     # MongoDB connection
β”‚   β”‚   β”‚   └── πŸ“„ redis.js        # Redis client
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ“‚ models/             # Mongoose schemas
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ User.js         # User schema (email, password, role)
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ Task.js         # Task schema (title, status, priority)
β”‚   β”‚   β”‚   └── πŸ“„ Note.js         # Note schema (title, content, tags)
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ“‚ controllers/        # Business logic
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ authController.js    # Register, login, refresh
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ taskController.js    # Task CRUD operations
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ noteController.js    # Note CRUD operations
β”‚   β”‚   β”‚   └── πŸ“„ userController.js    # User management (admin)
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ“‚ routes/             # API endpoints
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ authRoutes.js        # /api/v1/auth/*
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ taskRoutes.js        # /api/v1/tasks/*
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ noteRoutes.js        # /api/v1/notes/*
β”‚   β”‚   β”‚   └── πŸ“„ userRoutes.js        # /api/v1/users/* (admin)
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ“‚ middleware/         # Express middleware
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ auth.js              # JWT verification (protect)
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ authorize.js         # Role-based authorization
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ errorHandler.js      # Global error handler
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ rateLimiter.js       # Rate limiting
β”‚   β”‚   β”‚   β”‚
β”‚   β”‚   β”‚   └── πŸ“‚ validators/          # Input validation
β”‚   β”‚   β”‚       β”œβ”€β”€ πŸ“„ authValidator.js
β”‚   β”‚   β”‚       └── πŸ“„ resourceValidator.js
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ“‚ utils/              # Helper functions
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ bcryptHelper.js      # Password hashing
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ jwt.js               # Token generation/verification
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ errorFactory.js      # Error creation utilities
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ queryHelper.js       # Query utilities
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ redisCacheHelper.js  # Redis operations
β”‚   β”‚   β”‚   └── πŸ“„ validators.js        # Validation utilities
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ“‚ __tests__/          # Jest test suite
β”‚   β”‚   β”‚   β”œβ”€β”€ πŸ“„ auth.test.js         # Authentication tests
β”‚   β”‚   β”‚   └── πŸ“„ setup.js             # Test configuration
β”‚   β”‚   β”‚
β”‚   β”‚   └── πŸ“‚ swagger/            # Swagger configuration
β”‚   β”‚
β”‚   └── πŸ“‚ postman/
β”‚       └── πŸ“„ PrimeTrade-API.postman_collection.json
β”‚
└── πŸ“‚ client/                     # Frontend Next.js/React
    β”œβ”€β”€ πŸ“„ package.json
    β”œβ”€β”€ πŸ“„ next.config.mjs
    β”œβ”€β”€ πŸ“„ tailwind.config.js
    β”œβ”€β”€ πŸ“„ eslint.config.mjs
    β”œβ”€β”€ πŸ“„ .env.local              # Frontend env (create locally)
    β”œβ”€β”€ πŸ“„ Dockerfile
    β”œβ”€β”€ πŸ“„ README.md               # Frontend documentation
    β”‚
    β”œβ”€β”€ πŸ“‚ src/app/
    β”‚   β”œβ”€β”€ πŸ“„ layout.js           # Root layout
    β”‚   β”œβ”€β”€ πŸ“„ page.js             # Home page
    β”‚   β”œβ”€β”€ πŸ“„ globals.css         # Global styles
    β”‚   β”‚
    β”‚   β”œβ”€β”€ πŸ“‚ (auth)/             # Auth pages
    β”‚   β”‚   β”œβ”€β”€ πŸ“‚ login/
    β”‚   β”‚   β”‚   └── πŸ“„ page.js
    β”‚   β”‚   └── πŸ“‚ register/
    β”‚   β”‚       └── πŸ“„ page.js
    β”‚   β”‚
    β”‚   β”œβ”€β”€ πŸ“‚ dashboard/          # Protected dashboard
    β”‚   β”‚   β”œβ”€β”€ πŸ“„ layout.js
    β”‚   β”‚   β”œβ”€β”€ πŸ“„ page.js         # Dashboard overview
    β”‚   β”‚   β”‚
    β”‚   β”‚   β”œβ”€β”€ πŸ“‚ tasks/
    β”‚   β”‚   β”‚   └── πŸ“„ page.js     # Task management
    β”‚   β”‚   β”‚
    β”‚   β”‚   β”œβ”€β”€ πŸ“‚ notes/
    β”‚   β”‚   β”‚   └── πŸ“„ page.js     # Note management
    β”‚   β”‚   β”‚
    β”‚   β”‚   └── πŸ“‚ admin/
    β”‚   β”‚       └── πŸ“„ page.js     # Admin panel
    β”‚   β”‚
    β”‚   β”œβ”€β”€ πŸ“‚ components/         # Reusable UI components
    β”‚   β”‚   β”œβ”€β”€ πŸ“„ Navbar.js
    β”‚   β”‚   β”œβ”€β”€ πŸ“„ Modal.js
    β”‚   β”‚   β”œβ”€β”€ πŸ“„ TaskForm.js
    β”‚   β”‚   β”œβ”€β”€ πŸ“„ NoteForm.js
    β”‚   β”‚   └── πŸ“„ ProtectedRoute.js
    β”‚   β”‚
    β”‚   β”œβ”€β”€ πŸ“‚ context/            # React Context
    β”‚   β”‚   └── πŸ“„ AuthContext.js  # Authentication state
    β”‚   β”‚
    β”‚   └── πŸ“‚ lib/                # Utility functions
    β”‚       β”œβ”€β”€ πŸ“„ api.js          # API client wrapper
    β”‚       └── πŸ“„ toast.js        # Toast notification utilities
    β”‚
    └── πŸ“‚ public/                # Static assets


πŸ“š API Documentation

Access Swagger UI

Once the backend is running, visit: http://localhost:5000/api-docs

Base URL

http://localhost:5000/api/v1

Core Endpoints

Authentication

Method Endpoint Description Auth Required
POST /auth/register Register new user ❌
POST /auth/login Login user ❌
POST /auth/refresh Refresh access token ❌
GET /auth/me Get current user profile βœ…
POST /auth/logout Logout user βœ…

Tasks

Method Endpoint Description Auth Required
GET /tasks Get all user tasks βœ…
POST /tasks Create new task βœ…
GET /tasks/:id Get specific task βœ…
PUT /tasks/:id Update task βœ…
DELETE /tasks/:id Delete task βœ…
GET /tasks/status/:status Filter by status βœ…

Notes

Method Endpoint Description Auth Required
GET /notes Get all user notes βœ…
POST /notes Create new note βœ…
GET /notes/:id Get specific note βœ…
PUT /notes/:id Update note βœ…
DELETE /notes/:id Delete note βœ…
GET /notes/public Get public notes ❌
GET /notes/tags/:tag Filter by tag βœ…

Users (Admin Only)

Method Endpoint Description Auth Required
GET /users Get all users βœ… (Admin)
GET /users/:id Get specific user βœ… (Admin)
PUT /users/:id Update user βœ… (Admin)
DELETE /users/:id Delete user βœ… (Admin)
PUT /users/:id/role Change user role βœ… (Admin)

Example Requests

Register

curl -X POST http://localhost:5000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "username": "johndoe",
    "email": "john@example.com",
    "password": "SecurePass123"
  }'

Login

curl -X POST http://localhost:5000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "john@example.com",
    "password": "SecurePass123"
  }'

Create Task

curl -X POST http://localhost:5000/api/v1/tasks \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "title": "Complete project",
    "description": "Finish the REST API",
    "priority": "high",
    "status": "in-progress",
    "dueDate": "2026-04-15"
  }'

Get Tasks

curl -X GET http://localhost:5000/api/v1/tasks \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

πŸ”¨ Development Guide

Backend Development

  1. Start development server
cd server
npm run dev
  1. Run tests
npm test                # Run all tests
npm run test:watch    # Run tests in watch mode
npm run test:coverage # Generate coverage report
  1. Make changes
  • Edit files in src/ directory
  • Server will auto-reload (nodemon)
  • Check http://localhost:5000 for changes
  1. Add new endpoints
  • Create controller in src/controllers/
  • Create routes in src/routes/
  • Add Swagger JSDoc comments
  • Import routes in src/app.js

Frontend Development

  1. Start development server
cd client
npm run dev
  1. Build for production
npm run build
npm start
  1. Lint code
npm run lint
  1. Make changes
  • Edit files in src/app/
  • Browser will auto-refresh
  • Check http://localhost:3000 for changes

πŸ” Security Features

Authentication

  • βœ… JWT tokens with expiration
  • βœ… Refresh token rotation
  • βœ… httpOnly cookies (XSS protection)
  • βœ… Secure password hashing (bcrypt, salt rounds: 10)

Authorization

  • βœ… Role-based access control (RBAC)
  • βœ… Route protection middleware
  • βœ… User data isolation

Input Protection

  • βœ… Input validation (express-validator)
  • βœ… Sanitization (express-mongo-sanitize, xss-clean)
  • βœ… MongoDB injection prevention
  • βœ… XSS protection

Network Security

  • βœ… CORS with specific origins
  • βœ… Security headers (Helmet.js)
  • βœ… Rate limiting on auth endpoints
  • βœ… HTTPS ready

πŸ“ˆ Scalability

Current Optimizations

  1. Stateless API Design

    • No server-side session storage
    • Scales horizontally with load balancers
    • Any server instance can handle any request
  2. Caching Layer (Redis)

    • Reduces database queries by 60-80%
    • Faster response times for frequently accessed data
    • Cache invalidation on updates
  3. Database Indexing

    • Indexes on userId, status, priority fields
    • Compound indexes for common queries
    • Reduced query execution time
  4. Pagination

    • Prevents large data transfers
    • Supports limit and skip parameters
    • Better performance for large datasets

Future Scalability Improvements

  • Message queues (Bull/RabbitMQ) for async tasks
  • Database replication and sharding
  • API Gateway for routing
  • Microservices architecture
  • Kubernetes deployment
  • CDN for static assets
  • GraphQL support

See SCALABILITY.md for detailed information.


πŸ› Troubleshooting

Common Issues

MongoDB Connection Error

Error: connect ECONNREFUSED 127.0.0.1:27017

Solution:

# Check if MongoDB is running
mongosh

# If not running, start it:
# Linux: systemctl start mongod
# Mac: brew services start mongodb-community
# Windows: Use MongoDB GUI or set MONGODB_URI to MongoDB Atlas

Redis Connection Error

Error: connect ECONNREFUSED 127.0.0.1:6379

Solution:

# Check if Redis is running
redis-cli ping

# If not running, start it:
# Linux: service redis-server start
# Mac: brew services start redis
# Windows: Use Redis GUI or cloud service

Port Already in Use

Error: listen EADDRINUSE: address already in use :::5000

Solution:

# Find process using port 5000
lsof -i :5000  # Mac/Linux
netstat -ano | findstr :5000  # Windows

# Kill the process (Mac/Linux)
kill -9 <PID>

# Or use a different port
PORT=5001 npm run dev

JWT Token Expired

Error: Token expired. Please login again

Solution:

  • Use /api/v1/auth/refresh endpoint to get new access token
  • Frontend automatically handles token refresh

CORS Error in Browser

Access to XMLHttpRequest blocked by CORS policy

Solution:

  • Check FRONTEND_URL in .env matches your frontend URL
  • Ensure backend is running
  • Clear browser cache

Debug Mode

Enable verbose logging:

# Backend
DEBUG=app:* npm run dev

# Frontend
NEXT_DEBUG=true npm run dev

πŸ“ Testing

Backend Tests

cd server

# Run all tests
npm test

# Run specific file
npm test -- auth.test.js

# Watch mode
npm run test:watch

# Coverage report
npm run test:coverage

Manual Testing

  1. Using Postman

    • Import server/postman/PrimeTrade-API.postman_collection.json
    • Create environment with BASE_URL and TOKEN
    • Run requests
  2. Using cURL

  3. Using Frontend


πŸš€ Deployment

Docker Deployment (Recommended)

# Build and run
docker-compose up -d

# View logs
docker-compose logs -f

# Stop services
docker-compose down

# Clean up volumes
docker-compose down -v

Production Checklist

  • Update JWT secrets with strong random values
  • Set NODE_ENV=production
  • Use production MongoDB URI
  • Use production Redis URI
  • Enable HTTPS/SSL
  • Set proper CORS origins
  • Enable monitoring and logging
  • Setup backup strategy
  • Configure rate limiting appropriately
  • Test all endpoints

πŸ“œ License

ISC


🀝 Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“§ Support

For issues, questions, or suggestions:

  • Check Troubleshooting section
  • Review API documentation at /api-docs
  • Check backend logs: docker-compose logs backend
  • Check frontend logs: docker-compose logs frontend

πŸŽ“ Learning Resources


Happy coding! πŸš€ npm install


3. **Create environment file**
```bash
cp .env.example .env
  1. Update .env with your configuration
MONGODB_URI=mongodb://localhost:27017/primetrade
REDIS_URL=redis://localhost:6379
JWT_SECRET=your-secret-key-change-this
JWT_REFRESH_SECRET=your-refresh-secret-change-this
FRONTEND_URL=http://localhost:3000
  1. Start the server
npm run dev

The backend will be available at http://localhost:5000

Frontend Setup

  1. Navigate to client directory
cd client
  1. Install dependencies
npm install
  1. Create environment file
cp .env.local.example .env.local
  1. Update .env.local
NEXT_PUBLIC_API_URL=http://localhost:5000/api/v1
  1. Start the development server
npm run dev

The frontend will be available at http://localhost:3000

πŸ“ Project Structure

primetrade/
β”œβ”€β”€ server/                 # Backend API
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ config/        # Configuration files
β”‚   β”‚   β”œβ”€β”€ models/        # Mongoose models
β”‚   β”‚   β”œβ”€β”€ controllers/   # Route controllers
β”‚   β”‚   β”œβ”€β”€ routes/        # API routes
β”‚   β”‚   β”œβ”€β”€ middleware/    # Custom middleware
β”‚   β”‚   β”œβ”€β”€ utils/         # Helper functions
β”‚   β”‚   └── app.js         # Express app
β”‚   β”œβ”€β”€ .env.example
β”‚   β”œβ”€β”€ Dockerfile
β”‚   └── package.json
β”‚
β”œβ”€β”€ client/                # Frontend Next.js
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   └── app/
β”‚   β”‚       β”œβ”€β”€ dashboard/ # Protected dashboard
β”‚   β”‚       β”œβ”€β”€ login/     # Login page
β”‚   β”‚       β”œβ”€β”€ register/  # Register page
β”‚   β”‚       β”œβ”€β”€ components/# Reusable components
β”‚   β”‚       β”œβ”€β”€ context/   # React contexts
β”‚   β”‚       └── lib/       # Utilities
β”‚   β”œβ”€β”€ .env.local.example
β”‚   β”œβ”€β”€ Dockerfile
β”‚   └── package.json
β”‚
β”œβ”€β”€ docker-compose.yml     # Multi-container setup
β”œβ”€β”€ SCALABILITY.md         # Scalability documentation
└── README.md              # This file

πŸ” Authentication Flow

  1. Register: Create a new account at /register

    • Default role: user
    • Can specify admin role during registration
  2. Login: Authenticate at /login

    • Receives JWT access token (15 min expiry)
    • Receives refresh token (7 day expiry)
  3. Access Protected Routes: Include token in requests

    Authorization: Bearer <your-jwt-token>
    
  4. Refresh Token: When access token expires

    • Call /api/v1/auth/refresh with refresh token
    • Receive new access token

πŸ“š API Documentation

Swagger UI

Once the backend is running, visit http://localhost:5000/api-docs for interactive API documentation.

Main Endpoints

Authentication

  • POST /api/v1/auth/register - Register new user
  • POST /api/v1/auth/login - Login user
  • POST /api/v1/auth/refresh - Refresh access token
  • GET /api/v1/auth/me - Get current user profile

Tasks

  • GET /api/v1/tasks - Get all tasks
  • POST /api/v1/tasks - Create task
  • GET /api/v1/tasks/:id - Get task by ID
  • PUT /api/v1/tasks/:id - Update task
  • DELETE /api/v1/tasks/:id - Delete task
  • GET /api/v1/tasks/status/:status - Filter by status

Notes

  • GET /api/v1/notes - Get all notes
  • POST /api/v1/notes - Create note
  • GET /api/v1/notes/:id - Get note by ID
  • PUT /api/v1/notes/:id - Update note
  • DELETE /api/v1/notes/:id - Delete note
  • GET /api/v1/notes/public - Get public notes (no auth)
  • GET /api/v1/notes/tags/:tag - Filter by tag

Users (Admin Only)

  • GET /api/v1/users - Get all users
  • GET /api/v1/users/:id - Get user by ID
  • PUT /api/v1/users/:id - Update user
  • DELETE /api/v1/users/:id - Delete user
  • PUT /api/v1/users/:id/role - Change user role

πŸ”’ Security Features

  • Password Hashing: bcrypt with 10 salt rounds
  • JWT Tokens: Secure token-based authentication
  • Role-Based Access: User and admin roles
  • Input Validation: express-validator on all endpoints
  • Rate Limiting: 5 requests per 15 minutes on auth endpoints
  • CORS: Configured for specific origins
  • Security Headers: Helmet.js
  • NoSQL Injection Prevention: express-mongo-sanitize
  • XSS Protection: Input sanitization

⚑ Performance Features

Redis Caching

  • User tasks: 2-minute TTL
  • User notes: 2-minute TTL
  • Public notes: 5-minute TTL
  • Automatic cache invalidation on updates

Database Optimization

  • Indexed fields for fast queries
  • Connection pooling
  • Lean queries for read operations

πŸ“Š Database Schema

Users

{
  username: String (unique),
  email: String (unique),
  password: String (hashed),
  role: String (user|admin),
  createdAt: Date,
  updatedAt: Date
}

Tasks

{
  title: String,
  description: String,
  status: String (pending|in-progress|completed),
  priority: String (low|medium|high),
  userId: ObjectId (ref: User),
  dueDate: Date,
  createdAt: Date,
  updatedAt: Date
}

Notes

{
  title: String,
  content: String,
  tags: [String],
  userId: ObjectId (ref: User),
  isPublic: Boolean,
  createdAt: Date,
  updatedAt: Date
}

πŸ§ͺ Testing

Backend Testing

cd server
npm test

Frontend Testing

cd client
npm test

Manual Testing

Use the Swagger UI at http://localhost:5000/api-docs to test all API endpoints interactively.

πŸ“ˆ Scalability

See SCALABILITY.md for detailed information on:

  • Current architecture scalability
  • Horizontal scaling strategies
  • Future enhancements (microservices, message queues, etc.)
  • Monitoring and observability
  • Auto-scaling with Kubernetes
  • Performance optimization tips

🐳 Docker Deployment

Build and Run

docker-compose up -d

View Logs

docker-compose logs -f

Stop Services

docker-compose down

Rebuild After Code Changes

docker-compose up -d --build

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Languages