AI-Powered Smart Study Platform
Plan smarter, track progress, quiz yourself, and learn with an AI tutor β all in one place.
Features β’
Tech Stack β’
Architecture β’
Getting Started β’
API Docs β’
Deployment
π§ AI-Powered Study Plan Generator
Generate personalized study plans using Google Gemini AI . Input your exam date, subjects, and daily availability β the AI creates a day-by-day schedule with specific topics and time allocations. Falls back gracefully to a smart dummy generator when AI is unavailable.
π AI-Generated Quizzes
Take dynamically generated multiple-choice quizzes on any subject. Questions are created on-the-fly by Gemini AI with real-time grading and detailed result tracking. Falls back to a curated question bank when needed.
π€ AI Tutor (Chat Assistant)
Get instant academic help from an AI tutor. The assistant maintains conversation context, adapts to your class level, and ends each response with a practice question. Includes daily rate limiting (20 messages/day on Free plan).
Study Streak Tracking β Consecutive day counter
Weekly/Monthly Reports β Hours studied with daily & subject breakdown
Quiz Performance β Average scores over time
Gamification β Points system (10 pts per quiz, 5 pts per study hour)
π Subject & Chapter Management
Add/remove subjects with auto-generated chapters
Track chapter status: Not Started β Learning β Completed
Soft-delete support for safe removals
Visual progress indicators
Centralized view of all key metrics: current study plan, weekly chart, subject progress, task list, and AI tips.
π Enterprise-Grade Security
JWT with access + refresh token rotation
Password hashing (bcrypt, 12 rounds)
Helmet security headers
Rate limiting (200 req/15min per IP)
NoSQL injection prevention (mongo-sanitize)
Zod request validation
HTTP-only cookies for refresh tokens
Payload size limits (10kb)
Layer
Technology
Runtime
Node.js 20+
Framework
Express.js 4.21
Database
MongoDB + Mongoose 8.x ODM
Auth
JWT (access 15m, refresh 7d) + bcryptjs
Validation
Zod 4.x
AI
Google Gemini AI (@google/generative-ai)
Logging
Winston 3.x
Security
Helmet, CORS, express-rate-limit, express-mongo-sanitize
Architecture
Modular MVC (controllers, services, routes, models)
Layer
Technology
Framework
React 19
Build Tool
Vite 8.x
Routing
React Router 7.x
Styling
Tailwind CSS 4.x
Icons
Lucide React
Charts
Recharts 3.x
HTTP Client
Axios 1.x
Linting
ESLint 10.x
Deployment
Vercel (with SPA rewrites)
Production-Grade Directory Structure
studyflow-ai/
β
βββ backend/ # π₯ Express API Server
β βββ src/
β β βββ config/
β β β βββ db.js # MongoDB connection
β β β βββ env.js # Zod-enforced env validation
β β β
β β βββ middleware/
β β β βββ validate.js # Zod schema validation middleware
β β β βββ verifyToken.js # JWT access token verification
β β β
β β βββ models/ # Mongoose schemas
β β β βββ User.js # User with password hashing & refreshToken
β β β βββ Subject.js # Subjects with soft-delete
β β β βββ Chapter.js # Chapters with status tracking
β β β βββ StudyPlan.js # Day-by-day study plans
β β β βββ StudyLog.js # Study session logs
β β β βββ QuizAttempt.js # Quiz attempt records
β β β
β β βββ modules/ # π§© Feature modules (bounded contexts)
β β β βββ auth/ # Authentication & authorization
β β β β βββ auth.controller.js
β β β β βββ auth.service.js # Business logic + transactions
β β β β βββ auth.route.js
β β β β βββ auth.validator.js # Zod schemas
β β β β
β β β βββ users/ # User profile management
β β β β βββ users.controller.js
β β β β βββ users.route.js
β β β β
β β β βββ subjects/ # Subject CRUD with soft-delete
β β β β βββ subjects.controller.js
β β β β βββ subjects.route.js
β β β β
β β β βββ chapters/ # Chapter management & status
β β β β βββ chapters.controller.js
β β β β βββ chapters.route.js
β β β β
β β β βββ studyPlan/ # AI + fallback plan generation
β β β β βββ studyPlan.controller.js
β β β β βββ studyPlan.service.js # Dummy plan generator
β β β β βββ studyPlan.route.js
β β β β
β β β βββ quiz/ # AI + fallback quiz engine
β β β β βββ quiz.controller.js
β β β β βββ quiz.route.js
β β β β
β β β βββ studyLogs/ # Study session tracking
β β β β βββ studyLogs.controller.js
β β β β βββ studyLogs.route.js
β β β β
β β β βββ dashboard/ # Aggregated stats
β β β β βββ dashboard.controller.js
β β β β βββ dashboard.route.js
β β β β
β β β βββ aiChat/ # Gemini AI tutor
β β β βββ aiChat.controller.js
β β β βββ aiChat.route.js
β β β
β β βββ utils/
β β βββ ApiError.js # Custom operational error class
β β βββ catchAsync.js # Async error wrapper
β β βββ geminiClient.js # Gemini API client (timeout, truncation guard)
β β βββ helpers.js # Markdown stripper, quiz validator
β β βββ logger.js # Winston logger (console + file transports)
β β
β βββ server.js # π Entry point (env validation, security, routes)
β βββ package.json
β βββ .env.example # Template for environment variables
β
βββ frontend/ # π¨ React SPA
β βββ src/
β β βββ api/ # πΈ API client layer (Axios)
β β β βββ axios.js # Configured instance with interceptors
β β β βββ auth.js # Auth endpoints
β β β βββ subjects.js
β β β βββ chapters.js
β β β βββ studyPlan.js
β β β βββ quiz.js
β β β βββ studyLogs.js
β β β βββ dashboard.js
β β β βββ aiChat.js
β β β βββ users.js
β β β
β β βββ context/ # π React contexts
β β β βββ AuthContext.jsx # Auth state + token management
β β β
β β βββ components/ # π§© Reusable UI components
β β β βββ Dashboard.jsx # Dashboard layout
β β β βββ Sidebar.jsx # Navigation sidebar
β β β βββ Topbar.jsx # Top navigation bar
β β β βββ Navbar.jsx # Landing page navbar
β β β βββ Hero.jsx # Landing page hero
β β β βββ Features.jsx
β β β βββ Pricing.jsx
β β β βββ Footer.jsx
β β β βββ StatsRow.jsx
β β β βββ WeeklyChart.jsx # Recharts weekly chart
β β β βββ StudyPlanner.jsx
β β β βββ StudyPlanCard.jsx
β β β βββ PlanGeneratorForm.jsx
β β β βββ PlanSummaryPanel.jsx
β β β βββ SubjectCard.jsx
β β β βββ SubjectProgress.jsx
β β β βββ ChapterDrawer.jsx
β β β βββ ChapterRow.jsx
β β β βββ TaskList.jsx
β β β βββ TaskRow.jsx
β β β βββ QuizForm.jsx
β β β βββ QuizPage.jsx
β β β βββ QuizResultCard.jsx
β β β βββ QuestionCard.jsx
β β β βββ AiAssistant.jsx
β β β βββ ChatBubble.jsx
β β β βββ ChatTab.jsx
β β β βββ TypingIndicator.jsx
β β β βββ AITipCard.jsx
β β β βββ Analytics.jsx
β β β βββ Gamification.jsx
β β β βββ Settings.jsx
β β β βββ AccountTab.jsx
β β β βββ ProfileTab.jsx
β β β βββ NotificationsTab.jsx
β β β βββ PreferencesTab.jsx
β β β βββ SubscriptionTab.jsx
β β β βββ DangerZoneTab.jsx
β β β βββ LoginPage.jsx
β β β βββ AddSubjectModal.jsx
β β β βββ DayCard.jsx
β β β βββ OnboardingFlow.jsx
β β β βββ ProtectedRoute.jsx
β β β βββ StatusBadge.jsx
β β β βββ ToggleSwitch.jsx
β β β βββ Toast.jsx
β β β βββ ... more
β β β
β β βββ pages/ # π Route pages (re-export from components)
β β β βββ Dashboard.jsx
β β β βββ Landing.jsx
β β β βββ Login.jsx
β β β βββ Planner.jsx
β β β βββ Subjects.jsx
β β β βββ AiAssistant.jsx
β β β βββ Quiz.jsx
β β β βββ Analytics.jsx
β β β βββ Settings.jsx
β β β βββ Onboarding.jsx
β β β βββ NotFound.jsx
β β β
β β βββ App.jsx # π§ Root component (routing + providers)
β β βββ main.jsx # π Entry point
β β βββ index.css # Tailwind + custom animations
β β
β βββ index.html
β βββ vite.config.js
β βββ vercel.json # SPA rewrites for Vercel
β βββ package.json
β
βββ doc/
β βββ implementation_plan.md # Refactoring plan documentation
β
βββ setup.md # Deployment guide (Bengali)
βββ .gitignore
βββ README.md # π You are here
Key Architectural Decisions
Decision
Rationale
Modular monolith (modules/)
Feature-based grouping instead of technical layers β higher cohesion, easier to extract microservices later
Service layer
Business logic extracted from controllers β testable, reusable, keeps controllers thin
Soft delete
Subjects & chapters use isDeleted flag + query middleware β reversible, audit-friendly
AI fallback chain
Gemini AI β dummy generator / question bank β zero-downtime resilience
Token rotation
Refresh tokens are rotated on each use β limits stolen-token window
MongoDB transactions
Registration uses transactions for data consistency; falls back gracefully on single-node setups
JWT split secrets
Separate JWT_ACCESS_SECRET and JWT_REFRESH_SECRET β compartmentalized compromise
Rate limiting
Global (200/15min) + per-feature (AI chat: 20/day) β multi-layer abuse prevention
Zod validation
Runtime + type safety without TypeScript compilation overhead
Lazy loading
React.lazy() for all page components β smaller initial bundle
ββββββββββββ HTTPS ββββββββββββββββββββ Mongoose ββββββββββββ
β Browser β βββββββββββββββΆ β Express Server β βββββββββββββββββββΆ β MongoDB β
β (React) β βββββββββββββββ β (backend/) β βββββββββββββββββββ β β
ββββββββββββ β β ββββββββββββ
β βββββββββββββββ β
β β JWT Auth β β
β β Middleware β β
β ββββββββ¬βββββββ β
β β β
β ββββββββΌβββββββ β ββββββββββββββββ
β β Controllers β β β Google β
β ββββββββ¬βββββββ β β Gemini AI β
β β β β β
β ββββββββΌβββββββ β ββββββββ¬ββββββββ
β β Services β ββΌββββββββββββΆβ
β ββββββββ¬βββββββ β ββββββββ€
β β β
β ββββββββΌβββββββ β
β β Models β β
β βββββββββββββββ β
ββββββββββββββββββββ
Node.js 20+ (with --env-file support)
MongoDB (local or Atlas )
Google Gemini API Key (Get one free )
git clone https://github.com/yourusername/studyflow-ai.git
cd studyflow-ai
# Install backend dependencies
cd backend
npm install
# Install frontend dependencies
cd ../frontend
npm install
2οΈβ£ Configure Environment
# Backend environment
cp .env.example .env
# Edit .env with your values
.env file (backend/):
PORT = 5000
NODE_ENV = development
MONGO_URI = mongodb+srv://user:pass@cluster.mongodb.net/studyflow?retryWrites=true
JWT_SECRET = your-super-secret-key-min-8-chars
JWT_ACCESS_SECRET = your-access-secret-min-8-chars
JWT_REFRESH_SECRET = your-refresh-secret-min-8-chars
GEMINI_API_KEY = your-gemini-api-key
FRONTEND_URL = http://localhost:5173
3οΈβ£ Run Development Servers
# Terminal 1: Backend (auto-restart on changes)
cd backend
npm run dev
# Terminal 2: Frontend
cd frontend
npm run dev
# Backend
cd backend && npm start
# Frontend
cd frontend && npm run build && npm run preview
All API routes are prefixed with /api/v1.
Method
Endpoint
Description
Auth
POST
/auth/register
Create account + generate plan
β
POST
/auth/login
Login
β
POST
/auth/refresh
Refresh access token
β (cookie)
POST
/auth/logout
Logout (clear refresh token)
β
GET
/auth/me
Get current user
β
Method
Endpoint
Description
Auth
GET
/users/profile
Get user profile
β
PUT
/users/profile
Update profile
β
Method
Endpoint
Description
Auth
GET
/subjects
List all subjects
β
POST
/subjects
Create subject (auto-creates chapters)
β
PUT
/subjects/:id
Update subject
β
DELETE
/subjects/:id
Soft-delete subject
β
Method
Endpoint
Description
Auth
GET
/chapters/:subjectId
List chapters for subject
β
POST
/chapters
Create chapter
β
PATCH
/chapters/:id/status
Update chapter status
β
DELETE
/chapters/:id
Soft-delete chapter
β
Method
Endpoint
Description
Auth
GET
/study-plan
Get current plan
β
POST
/study-plan/generate
Generate new AI plan
β
PATCH
/study-plan/:planId/day/:dayIndex/task/:taskId
Toggle task completion
β
Method
Endpoint
Description
Auth
GET
/quiz/questions?subject=X&count=5&difficulty=medium
Get sample questions
β
POST
/quiz/submit
Submit quiz attempt
β
GET
/quiz/history?limit=20
Get quiz history
β
Method
Endpoint
Description
Auth
POST
/study-logs
Log study session
β
GET
/study-logs/weekly
Get weekly summary
β
GET
/study-logs/monthly
Get monthly summary
β
Method
Endpoint
Description
Auth
GET
/dashboard
Aggregated stats (streak, points, avg score, hours)
β
Method
Endpoint
Description
Auth
POST
/ai-chat/ask
Ask AI tutor (rate-limited: 20/day)
β
Method
Endpoint
Description
GET
/health
Health check (no prefix)
Field
Type
Notes
name
String
Required
email
String
Unique, lowercase
password
String
bcrypt(12), select: false
classLevel
String
e.g., "HSC", "Undergraduate"
goal
String
e.g., "Exam preparation"
subjects
[String]
Array of subject names
examDate
Date
Target exam date
plan
"free" | "pro"
Subscription tier
dailyAiMessages
Number
Resets daily
refreshToken
String
select: false
Field
Type
Notes
userId
ObjectId
Ref β User
name
String
Required
totalChapters
Number
Default 0
color
String
UI color indicator
isDeleted
Boolean
Soft-delete, select: false
Field
Type
Notes
subjectId
ObjectId
Ref β Subject
name
String
Required
status
"not-started" | "learning" | "completed"
Progress tracking
order
Number
Display ordering
isDeleted
Boolean
Soft-delete, select: false
Field
Type
Notes
userId
ObjectId
Ref β User
examDate
Date
Target date
dailyHours
Number
Default 4
days
[Day]
Sub-documents with tasks
Field
Type
Notes
userId
ObjectId
Ref β User
subject
String
Quiz subject
questions
[QuestionResult]
Full question data
score
Number
Correct answers
totalQuestions
Number
Total questions
Field
Type
Notes
userId
ObjectId
Ref β User
date
Date
Session date
hoursStudied
Number
β₯ 0
subject
String
Subject name
topic
String
Optional topic
Push code to GitHub
Create Web Service on Render
Configure:
Root Directory : backend
Build Command : npm install
Start Command : npm start
Add all environment variables in Render dashboard
Deploy
Import repo on Vercel
Configure:
Root Directory : frontend
Framework : Vite
Build Command : npm run build
Output Directory : dist
Add VITE_API_URL environment variable pointing to your Render backend
Deploy
π See setup.md for detailed deployment instructions (Bengali).
Measure
Implementation
Password hashing
bcrypt with 12 salt rounds
JWT access tokens
15-minute expiry
JWT refresh tokens
7-day expiry, rotated on use
HTTP-only cookies
Refresh tokens stored in cookies
Request validation
Zod middleware rejects malformed input
Rate limiting
200 requests per 15 minutes per IP
NoSQL injection
express-mongo-sanitize strips $ and .
Security headers
Helmet sets CSP, X-Frame-Options, etc.
Payload limit
JSON body limited to 10kb
CORS
Explicit whitelist + credentials: true
Soft delete
Data never truly lost
π§Ή Code Quality & Patterns
ES Modules ("type": "module") throughout
catchAsync wrapper β no try-catch boilerplate in controllers
Custom ApiError class β consistent operational error handling
Sentry-ready error format β global error handler produces structured JSON
Graceful AI fallbacks β Gemini β dummy logic β zero-downtime
Query middleware β automatic soft-delete filtering via Mongoose pre(/^find/)
Indexed queries β All frequent queries have MongoDB indexes
Environment validation β Zod schema at startup catches misconfiguration early
Auto-cleanup β Quiz cache purges entries older than 1 hour
Fork the repository
Create a feature branch (git checkout -b feat/amazing-feature)
Commit changes (git commit -m 'feat: add amazing feature')
Push to branch (git push origin feat/amazing-feature)
Open a Pull Request
We follow Conventional Commits :
feat: β New feature
fix: β Bug fix
refactor: β Code restructuring
docs: β Documentation
chore: β Maintenance
This project is licensed under the MIT License.
Built with β€οΈ using React, Node.js, MongoDB & Google Gemini AI