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.
- Overview
- Features
- Tech Stack
- Architecture
- Prerequisites
- Quick Start
- Environment Setup
- Project Structure
- API Documentation
- Development Guide
- Security Features
- Scalability
- Troubleshooting
- Contributing
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.
-
β 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
-
β 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
- β Multi-container Docker Compose setup
- β MongoDB containerization
- β Redis containerization
- β Networking between containers
- β Environment-based configuration
- β Production-ready settings
| 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+ |
| 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+ |
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 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 β
βββββββββββββββββββ
Before you begin, ensure you have the following installed:
- Node.js 18+ (Download)
- npm 9+ (comes with Node.js)
- MongoDB 7+ (local or MongoDB Atlas)
- Redis (local or Redis Cloud)
- Docker & Docker Compose (optional, for containerized deployment)
node --version # Should be v18+
npm --version # Should be 9+Docker Compose automatically sets up MongoDB, Redis, Backend, and Frontend with proper networking.
- Clone the repository
git clone <repository-url>
cd primetrade- Create environment file
# Copy the example env file
cp server/.env.example server/.env- Start all services
docker-compose up -d- Verify all services are running
docker-compose ps- Access the application
- Frontend: http://localhost:3000
- Backend API: http://localhost:5000
- API Documentation: http://localhost:5000/api-docs
- Postman Collection: Import
server/postman/PrimeTrade-API.postman_collection.json
- Stop all services
docker-compose down- 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 logsIf you prefer to run services locally without Docker:
Linux/Mac:
brew install mongodb-community
brew services start mongodb-communityWindows: Download from MongoDB
Verify:
mongosh # Should connect to MongoDB shellLinux:
sudo apt-get install redis-server
redis-serverMac:
brew install redis
brew services start redisWindows: Use Windows Subsystem for Linux (WSL) or Redis for Windows
Verify:
redis-cli ping # Should return PONGcd 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 startThe backend will start at http://localhost:5000
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 devThe frontend will start at http://localhost:3000
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>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/v1Use 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 16primetrade/
β
βββ π 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
Once the backend is running, visit: http://localhost:5000/api-docs
http://localhost:5000/api/v1
| 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 | β |
| 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 | β |
| 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 | β |
| 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) |
curl -X POST http://localhost:5000/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{
"username": "johndoe",
"email": "john@example.com",
"password": "SecurePass123"
}'curl -X POST http://localhost:5000/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "john@example.com",
"password": "SecurePass123"
}'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"
}'curl -X GET http://localhost:5000/api/v1/tasks \
-H "Authorization: Bearer YOUR_JWT_TOKEN"- Start development server
cd server
npm run dev- Run tests
npm test # Run all tests
npm run test:watch # Run tests in watch mode
npm run test:coverage # Generate coverage report- Make changes
- Edit files in
src/directory - Server will auto-reload (nodemon)
- Check
http://localhost:5000for changes
- Add new endpoints
- Create controller in
src/controllers/ - Create routes in
src/routes/ - Add Swagger JSDoc comments
- Import routes in
src/app.js
- Start development server
cd client
npm run dev- Build for production
npm run build
npm start- Lint code
npm run lint- Make changes
- Edit files in
src/app/ - Browser will auto-refresh
- Check
http://localhost:3000for changes
- β JWT tokens with expiration
- β Refresh token rotation
- β httpOnly cookies (XSS protection)
- β Secure password hashing (bcrypt, salt rounds: 10)
- β Role-based access control (RBAC)
- β Route protection middleware
- β User data isolation
- β Input validation (express-validator)
- β Sanitization (express-mongo-sanitize, xss-clean)
- β MongoDB injection prevention
- β XSS protection
- β CORS with specific origins
- β Security headers (Helmet.js)
- β Rate limiting on auth endpoints
- β HTTPS ready
-
Stateless API Design
- No server-side session storage
- Scales horizontally with load balancers
- Any server instance can handle any request
-
Caching Layer (Redis)
- Reduces database queries by 60-80%
- Faster response times for frequently accessed data
- Cache invalidation on updates
-
Database Indexing
- Indexes on userId, status, priority fields
- Compound indexes for common queries
- Reduced query execution time
-
Pagination
- Prevents large data transfers
- Supports limit and skip parameters
- Better performance for large datasets
- 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.
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 AtlasError: 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 serviceError: 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 devError: Token expired. Please login again
Solution:
- Use
/api/v1/auth/refreshendpoint to get new access token - Frontend automatically handles token refresh
Access to XMLHttpRequest blocked by CORS policy
Solution:
- Check
FRONTEND_URLin.envmatches your frontend URL - Ensure backend is running
- Clear browser cache
Enable verbose logging:
# Backend
DEBUG=app:* npm run dev
# Frontend
NEXT_DEBUG=true npm run devcd 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-
Using Postman
- Import
server/postman/PrimeTrade-API.postman_collection.json - Create environment with
BASE_URLandTOKEN - Run requests
- Import
-
Using cURL
- See examples in API Documentation
-
Using Frontend
- Access http://localhost:3000
- Test authentication flow
- Test CRUD operations
# 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- 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
ISC
Contributions are welcome! Please:
- Fork the repository
- Create feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
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
- JWT.io - JWT Documentation
- MongoDB Documentation
- Express.js Guide
- Next.js Documentation
- Redis Documentation
- REST API Best Practices
Happy coding! π npm install
3. **Create environment file**
```bash
cp .env.example .env
- Update
.envwith 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- Start the server
npm run devThe backend will be available at http://localhost:5000
- Navigate to client directory
cd client- Install dependencies
npm install- Create environment file
cp .env.local.example .env.local- Update
.env.local
NEXT_PUBLIC_API_URL=http://localhost:5000/api/v1- Start the development server
npm run devThe frontend will be available at http://localhost:3000
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
-
Register: Create a new account at
/register- Default role:
user - Can specify
adminrole during registration
- Default role:
-
Login: Authenticate at
/login- Receives JWT access token (15 min expiry)
- Receives refresh token (7 day expiry)
-
Access Protected Routes: Include token in requests
Authorization: Bearer <your-jwt-token> -
Refresh Token: When access token expires
- Call
/api/v1/auth/refreshwith refresh token - Receive new access token
- Call
Once the backend is running, visit http://localhost:5000/api-docs for interactive API documentation.
POST /api/v1/auth/register- Register new userPOST /api/v1/auth/login- Login userPOST /api/v1/auth/refresh- Refresh access tokenGET /api/v1/auth/me- Get current user profile
GET /api/v1/tasks- Get all tasksPOST /api/v1/tasks- Create taskGET /api/v1/tasks/:id- Get task by IDPUT /api/v1/tasks/:id- Update taskDELETE /api/v1/tasks/:id- Delete taskGET /api/v1/tasks/status/:status- Filter by status
GET /api/v1/notes- Get all notesPOST /api/v1/notes- Create noteGET /api/v1/notes/:id- Get note by IDPUT /api/v1/notes/:id- Update noteDELETE /api/v1/notes/:id- Delete noteGET /api/v1/notes/public- Get public notes (no auth)GET /api/v1/notes/tags/:tag- Filter by tag
GET /api/v1/users- Get all usersGET /api/v1/users/:id- Get user by IDPUT /api/v1/users/:id- Update userDELETE /api/v1/users/:id- Delete userPUT /api/v1/users/:id/role- Change user role
- 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
- User tasks: 2-minute TTL
- User notes: 2-minute TTL
- Public notes: 5-minute TTL
- Automatic cache invalidation on updates
- Indexed fields for fast queries
- Connection pooling
- Lean queries for read operations
{
username: String (unique),
email: String (unique),
password: String (hashed),
role: String (user|admin),
createdAt: Date,
updatedAt: Date
}{
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
}{
title: String,
content: String,
tags: [String],
userId: ObjectId (ref: User),
isPublic: Boolean,
createdAt: Date,
updatedAt: Date
}cd server
npm testcd client
npm testUse the Swagger UI at http://localhost:5000/api-docs to test all API endpoints interactively.
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-compose up -ddocker-compose logs -fdocker-compose downdocker-compose up -d --build- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request