Skip to content

About

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Β 
Β 

Latest commit

Β 

History

1,286 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

βš”οΈ CodePulse (DevBattle)

Nexus Spring of Code 2026 CI Build & Tests Security Shield Contributors PRs Welcome License: MIT

NSoC'26 Level 1 NSoC'26 Level 2 NSoC'26 Level 3

🌟 Official Participant in Nexus Spring of Code (NSoC / NWoC) 2026 β€” Winter Edition
A 45-day open-source program where maintainers and contributors collaborate to build real-world software.
πŸ“– Program Timeline: 19 Oct – 02 Dec 2026 | πŸ”— Official Portal: nsoc.in | πŸ’¬ Community: NSoC Discord Server

🌟 Hall of Fame & Contributors Wall

A heartfelt thank you to all the amazing developers contributing to CodePulse during Nexus Spring of Code (NSoC'26)! You are making developer analytics gamified and accessible to everyone. πŸŽ‰

code-with-abhi-i5
@code-with-abhi-i5

πŸ’» Contributor
πŸ”¨ 390 commits
Babin123456
@Babin123456

πŸ’» Contributor
πŸ”¨ 120 commits
pratikadamas
@pratikadamas

πŸ‘‘ Maintainer
πŸ”¨ 90 commits
divyanshAgarwal123
@divyanshAgarwal123

πŸ’» Contributor
πŸ”¨ 31 commits
Itssonia7
@Itssonia7

πŸ’» Contributor
πŸ”¨ 20 commits
Sarbajit-Sengupta
@Sarbajit-Sengupta

πŸ’» Contributor
πŸ”¨ 11 commits
Trunal2005
@Trunal2005

πŸ’» Contributor
πŸ”¨ 7 commits
aush5895
@aush5895

πŸ’» Contributor
πŸ”¨ 6 commits
nilesh0199
@nilesh0199

πŸ’» Contributor
πŸ”¨ 6 commits
Ankit-Kum-ar
@Ankit-Kum-ar

πŸ’» Contributor
πŸ”¨ 5 commits
bhavyasingh-sa
@bhavyasingh-sa

πŸ’» Contributor
πŸ”¨ 5 commits
shahkhushi0307
@shahkhushi0307

πŸ’» Contributor
πŸ”¨ 3 commits
sumittiwari1302
@sumittiwari1302

πŸ’» Contributor
πŸ”¨ 2 commits
chanchall26
@chanchall26

πŸ’» Contributor
πŸ”¨ 2 commits
tesfa27
@tesfa27

πŸ’» Contributor
πŸ”¨ 1 commits
yash-kumawat-0
@yash-kumawat-0

πŸ’» Contributor
πŸ”¨ 1 commits

πŸ’‘ Want to see your face here? Check out our CONTRIBUTING.md, pick an open NSoC Issue, and submit your PR! πŸš€


πŸ† Nexus Spring of Code (NSoC 2026) Points Structure

Label Points Scope / Used For
nsoc26 Mandatory Every NSoC issue and PR must carry this tag
level1 3 Pts Documentation, typo fixes, small UI/style tweaks
level2 5 Pts UI & Frontend components, layouts, responsive design, charts
level3 10 Pts Core business logic, backend APIs, database schema, complex features

⚠️ NSoC Guidelines: Every contributor must be officially assigned to an issue before opening a PR. PRs opened without prior assignment will be closed. Please read CONTRIBUTING.md before starting!


πŸ“– CodePulse (DevBattle) β€” Complete Project Architecture Document

Version: 1.0 | Last Updated: July 2026
Author: code-with-abhi-i5 | Repository: CodePulse on GitHub


πŸ“‹ Table of Contents

  1. Project Overview
  2. High-Level Architecture
  3. Technology Stack β€” Complete Breakdown
  4. Frontend Deep Dive (Next.js)
  5. Backend Deep Dive (NestJS)
  6. Database Architecture (PostgreSQL + Prisma)
  7. External APIs & Data Sources
  8. Internal API Routes (Next.js Server)
  9. Authentication Flow
  10. Caching & Performance Architecture
  11. Complete Folder Structure
  12. Feature Breakdown
  13. Data Flow Diagrams
  14. Environment Variables
  15. Deployment Architecture
  16. Development Setup Guide

1. Project Overview

CodePulse (branded as "DevBattle") is a full-stack GitHub Developer Analytics & Gamification Platform. It allows developers to:

  • Visualize their GitHub activity with beautiful charts and heatmaps.
  • Compare their coding stats against any other developer on GitHub.
  • Compete via Battles, Leaderboards, and Daily/Weekly Challenges.
  • Level Up with an XP system, Achievements, and collectible Badges.
  • Track repositories, commit patterns, and coding habits.

It is designed as a premium, enterprise-grade web application with a dark-mode-first aesthetic inspired by Vercel, Linear, and Raycast.


2. High-Level Architecture

The application follows a Monorepo-style structure with two independent services:

graph LR
    subgraph "Client (Browser)"
        A["Next.js Frontend<br/>Port 3000"]
    end

    subgraph "Server Layer"
        B["Next.js API Routes<br/>(Proxy + Cache)"]
        C["NestJS Backend<br/>Port 3001"]
    end

    subgraph "External"
        D["GitHub REST API<br/>api.github.com"]
        E["GitHub Contributions API<br/>github-contributions-api.deno.dev"]
    end

    subgraph "Data Layer"
        F["PostgreSQL<br/>(Supabase)"]
    end

    A -->|"fetch('/api/github/...')"| B
    A -->|"axios (apiClient)"| C
    B -->|"Server-Side fetch + Cache"| D
    B -->|"Streak Data"| E
    C -->|"Prisma ORM"| F
    C -->|"@octokit/rest"| D
Loading
Layer Technology Port Purpose
Frontend Next.js 16.2.9 (React 19) 3000 UI, Routing, SSR
Proxy/Cache Next.js API Routes 3000 GitHub API Proxy with Smart Caching
Backend NestJS 11 3001 Business Logic, Auth, Gamification
Database PostgreSQL (via Supabase) 5432 Persistent Data Storage
ORM Prisma 6.19 β€” Type-safe Database Access

3. Technology Stack β€” Complete Breakdown

3.1 Frontend Dependencies

Library Version What It Does
next 16.2.9 The React meta-framework. Handles routing, SSR, API routes, image optimization, code splitting. Uses App Router with (dashboard) route groups.
react / react-dom 19.2.4 The core UI library. Version 19 enables React Server Components, use() hook, and improved Suspense.
tailwindcss 4.x Utility-first CSS framework. All styling is done via Tailwind utility classes.
@tailwindcss/postcss 4.x PostCSS plugin that compiles Tailwind CSS at build time.
tw-animate-css 1.4.0 Provides pre-built CSS animation utilities for Tailwind (e.g., fade-in, slide-up).
motion (Framer Motion) 12.42.2 Powers all animations: page transitions, skeleton loading shimmers, hover effects, spring physics, staggered reveals.
echarts 6.1.0 The charting engine. Renders radar charts, contribution heatmaps, repository bubble charts, sparklines, and language distribution donuts.
echarts-for-react 3.0.6 React wrapper for ECharts. Provides the <ReactECharts> component used in all chart files.
recharts 3.9.2 Alternative charting library (used for simpler line/bar charts alongside ECharts).
lucide-react 1.23.0 Icon library. Every icon in the app (sidebar nav, stat cards, buttons) comes from Lucide. Provides 1,000+ SVG icons as React components.
@tanstack/react-query 5.101.2 Server state management. All backend API calls go through React Query hooks (useQuery, useMutation). Handles caching, refetching, loading states, and stale data.
@tanstack/react-query-devtools 5.101.2 Dev-only floating panel for inspecting React Query cache, active queries, and mutations.
axios 1.18.1 HTTP client for making requests to the NestJS backend (apiClient). Configured with interceptors for automatic JWT injection.
sonner 2.0.7 Toast notification library. Shows success/error/info toasts (bottom-right corner). Styled with glassmorphism.
next-themes 0.4.6 Theme management (dark/light mode toggle). Wraps the app in <ThemeProvider> and provides the useTheme() hook.
shadcn 4.12.0 UI component generator. Not a library itself β€” it copies beautiful, customizable components into src/components/ui/.
class-variance-authority (CVA) 0.7.1 Used by shadcn components to create variant-based CSS class mappings (e.g., button variants: primary, outline, ghost).
clsx 2.1.1 Utility for conditionally joining CSS class names. Used inside the cn() helper function.
tailwind-merge 3.6.0 Intelligently merges Tailwind classes, resolving conflicts (e.g., p-2 p-4 β†’ p-4). Used inside the cn() helper function.
cmdk 1.1.1 Command Palette (⌘K) component. Powers the global search/navigation overlay accessible from anywhere in the app.
react-resizable-panels 4.12.0 Provides resizable split-pane layouts. Used in dashboard views.
react-hook-form 7.80.0 Performant form library. Handles form state, validation, and submission without re-rendering the entire form.
@hookform/resolvers 5.4.0 Connects Zod validation schemas to React Hook Form.
zod 4.4.3 TypeScript-first schema validation library. Defines and validates data shapes for forms and API payloads.
@base-ui/react 1.6.0 Low-level UI primitives from the MUI team. Provides unstyled, accessible building blocks.
three 0.185.1 3D rendering engine (Three.js). Powers the 3D animated hero section on the landing page.
@react-three/fiber 9.6.1 React renderer for Three.js. Lets you write Three.js scenes as JSX components.
@react-three/drei 10.7.7 Collection of useful helpers for React Three Fiber (camera controls, loaders, materials, text).
gsap 3.15.0 GreenSock Animation Platform. Used for high-performance scroll-based animations and complex timeline sequences on the landing page.

3.2 Backend Dependencies

Library Version What It Does
@nestjs/common 11.0.1 Core NestJS framework. Provides decorators (@Controller, @Get, @Injectable), dependency injection, and module system.
@nestjs/core 11.0.1 The NestJS runtime engine.
@nestjs/platform-express 11.0.1 HTTP adapter using Express.js under the hood.
@nestjs/config 4.0.4 Configuration management. Loads .env variables and makes them injectable via ConfigService.
@nestjs/passport 11.0.5 Authentication middleware integration. Wraps Passport.js strategies for NestJS.
@nestjs/jwt 11.0.2 JWT (JSON Web Token) utilities. Signs and verifies tokens for user authentication.
@nestjs/swagger 11.4.5 Auto-generates OpenAPI/Swagger documentation from decorators. Accessible at /api/docs.
passport 0.7.0 Authentication framework. Provides the strategy pattern for different auth methods.
passport-jwt 4.0.1 JWT authentication strategy for Passport. Validates Bearer tokens from request headers.
@prisma/client 6.19.3 Auto-generated, type-safe database client. Provides methods like prisma.user.findUnique(), prisma.repository.findMany().
@octokit/rest 22.0.1 Official GitHub REST API client. Used by the SyncService to fetch user data, repos, and stats from GitHub.
axios 1.18.1 HTTP client (backup to Octokit for certain API calls).
class-validator 0.15.1 Decorator-based validation for DTOs. E.g., @IsString(), @IsNotEmpty() on request body properties.
class-transformer 0.5.1 Transforms plain objects to class instances and vice versa. Works with class-validator.
pg 8.22.0 PostgreSQL driver for Node.js. Used by Prisma internally to connect to the database.
dotenv 17.4.2 Loads environment variables from .env file into process.env.
rxjs 7.8.1 Reactive Extensions for JavaScript. Required by NestJS for observables in interceptors, guards, and pipes.
reflect-metadata 0.2.2 Polyfill for the Metadata Reflection API. Required by NestJS's decorator system.

3.3 Dev Dependencies

Tool Purpose
TypeScript 5.x Static type checking for both frontend and backend.
ESLint 9 Code linting and style enforcement.
Prettier 3.4 Code formatting (backend).
Jest 30 Unit testing framework (backend).
Supertest 7 HTTP assertion testing (backend e2e tests).
Prisma CLI 6.19 Database migration and schema management tool.
ts-node TypeScript execution engine for running scripts directly.
cross-env Cross-platform environment variable setting for npm scripts.

4. Frontend Deep Dive (Next.js)

4.1 App Router Structure

The frontend uses Next.js App Router with route groups:

src/app/
β”œβ”€β”€ page.tsx                    β†’ Landing Page (public, 3D hero + features)
β”œβ”€β”€ layout.tsx                  β†’ Root Layout (Inter font, metadata, Providers)
β”œβ”€β”€ providers.tsx                β†’ Client Providers (React Query, Theme, Toaster)
β”œβ”€β”€ globals.css                  β†’ Global styles + Tailwind imports
β”œβ”€β”€ not-found.tsx                β†’ Custom 404 page
β”œβ”€β”€ favicon.ico                  β†’ App icon
β”‚
β”œβ”€β”€ (auth)/                      β†’ Auth Route Group (no sidebar)
β”‚   β”œβ”€β”€ layout.tsx               β†’ Minimal auth layout
β”‚   β”œβ”€β”€ login/page.tsx           β†’ Login page
β”‚   └── signup/page.tsx          β†’ Signup page
β”‚
β”œβ”€β”€ (dashboard)/                 β†’ Dashboard Route Group (with sidebar)
β”‚   β”œβ”€β”€ layout.tsx               β†’ Dashboard layout (Sidebar + Topbar + CommandPalette)
β”‚   β”œβ”€β”€ dashboard/page.tsx       β†’ Main dashboard (stats overview)
β”‚   β”œβ”€β”€ analytics/page.tsx       β†’ Analytics page (charts, heatmaps)
β”‚   β”œβ”€β”€ repositories/page.tsx    β†’ Repository listing & details
β”‚   β”œβ”€β”€ compare/page.tsx         β†’ Developer Comparison (βš”οΈ the main feature you built)
β”‚   β”œβ”€β”€ battles/page.tsx         β†’ 1v1 Developer Battles
β”‚   β”œβ”€β”€ leaderboard/page.tsx     β†’ Global Rankings
β”‚   β”œβ”€β”€ challenges/page.tsx      β†’ Daily/Weekly Challenges
β”‚   β”œβ”€β”€ achievements/page.tsx    β†’ Achievements & Badges gallery
β”‚   β”œβ”€β”€ profile/page.tsx         β†’ User profile page
β”‚   └── settings/page.tsx        β†’ User settings
β”‚
β”œβ”€β”€ api/                         β†’ Next.js API Routes (Server-Side)
β”‚   └── github/
β”‚       └── developer/
β”‚           └── route.ts         β†’ GitHub data proxy with Smart Caching
β”‚
β”œβ”€β”€ auth/                        β†’ Auth utilities
β”‚   └── callback/page.tsx        β†’ GitHub OAuth callback handler
β”‚
└── maintenance/                 β†’ Maintenance mode page

4.2 Component Architecture

src/components/
β”œβ”€β”€ animations/
β”‚   β”œβ”€β”€ animated-counter.tsx     β†’ Numbers that count up with spring physics
β”‚   └── page-transition.tsx      β†’ Fade + slide animation between pages
β”‚
β”œβ”€β”€ cards/
β”‚   β”œβ”€β”€ achievement-card.tsx     β†’ Achievement display with rarity glow
β”‚   β”œβ”€β”€ challenge-card.tsx       β†’ Challenge card with progress bar
β”‚   β”œβ”€β”€ developer-rating-card.tsx β†’ Rating tier display (Bronze β†’ Grandmaster)
β”‚   β”œβ”€β”€ leaderboard-preview.tsx  β†’ Top developers mini-leaderboard
β”‚   β”œβ”€β”€ stat-card.tsx            β†’ Individual stat (commits, stars, etc.)
β”‚   └── welcome-hero-banner.tsx  β†’ Dashboard welcome banner with user greeting
β”‚
β”œβ”€β”€ charts/
β”‚   β”œβ”€β”€ commit-activity-chart.tsx       β†’ Weekly commit heatmap/bar chart
β”‚   β”œβ”€β”€ contribution-heatmap.tsx        β†’ GitHub-style green contribution grid
β”‚   β”œβ”€β”€ github-wrapped-banner.tsx       β†’ Annual "GitHub Wrapped" summary
β”‚   β”œβ”€β”€ global-ranking-meter.tsx        β†’ Circular gauge showing global rank
β”‚   β”œβ”€β”€ language-distribution.tsx       β†’ Donut chart of languages used
β”‚   β”œβ”€β”€ radar-compare-chart.tsx         β†’ Radar/Spider chart for developer comparison
β”‚   β”œβ”€β”€ repo-sparkline.tsx              β†’ Tiny inline sparkline for repo activity
β”‚   β”œβ”€β”€ repository-bubble-chart.tsx     β†’ Bubble chart showing repo sizes
β”‚   └── repository-growth.tsx           β†’ Line chart of repo growth over time
β”‚
β”œβ”€β”€ data-display/
β”‚   └── activity-timeline.tsx    β†’ Chronological activity feed
β”‚
β”œβ”€β”€ feedback/
β”‚   └── states.tsx               β†’ Empty states, loading states, error states
β”‚
β”œβ”€β”€ icons/
β”‚   └── github.tsx               β†’ Custom GitHub SVG icon component
β”‚
β”œβ”€β”€ layout/
β”‚   β”œβ”€β”€ sidebar.tsx              β†’ Main navigation sidebar (collapsible)
β”‚   β”œβ”€β”€ topbar.tsx               β†’ Top navigation bar (search, notifications, avatar)
β”‚   └── command-palette.tsx      β†’ ⌘K command palette for global search
β”‚
β”œβ”€β”€ modals/
β”‚   └── repo-quick-view.tsx      β†’ Repository detail modal/drawer
β”‚
β”œβ”€β”€ sections/
β”‚   └── hero-3d.tsx              β†’ Three.js 3D animated hero for landing page
β”‚
β”œβ”€β”€ theme-provider.tsx           β†’ Dark/Light mode provider wrapper
β”‚
└── ui/                          β†’ 30 shadcn/ui base components
    β”œβ”€β”€ accordion.tsx
    β”œβ”€β”€ alert.tsx
    β”œβ”€β”€ avatar.tsx
    β”œβ”€β”€ badge.tsx
    β”œβ”€β”€ breadcrumb.tsx
    β”œβ”€β”€ button.tsx
    β”œβ”€β”€ card.tsx
    β”œβ”€β”€ command.tsx
    β”œβ”€β”€ dialog.tsx
    β”œβ”€β”€ dropdown-menu.tsx
    β”œβ”€β”€ input.tsx
    β”œβ”€β”€ input-group.tsx
    β”œβ”€β”€ popover.tsx
    β”œβ”€β”€ progress.tsx
    β”œβ”€β”€ resizable.tsx
    β”œβ”€β”€ scroll-area.tsx
    β”œβ”€β”€ select.tsx
    β”œβ”€β”€ separator.tsx
    β”œβ”€β”€ sheet.tsx
    β”œβ”€β”€ sidebar.tsx
    β”œβ”€β”€ skeleton.tsx
    β”œβ”€β”€ slider.tsx
    β”œβ”€β”€ sonner.tsx
    β”œβ”€β”€ switch.tsx
    β”œβ”€β”€ table.tsx
    β”œβ”€β”€ tabs.tsx
    β”œβ”€β”€ textarea.tsx
    β”œβ”€β”€ toggle.tsx
    β”œβ”€β”€ toggle-group.tsx
    └── tooltip.tsx

4.3 Hooks

src/hooks/
β”œβ”€β”€ use-mobile.ts                β†’ Detects mobile viewport (responsive sidebar)
└── api/
    β”œβ”€β”€ use-auth.ts              β†’ useCurrentUser(), useLogin(), useLogout()
    β”œβ”€β”€ use-battles.ts           β†’ useBattles(), useCreateBattle()
    β”œβ”€β”€ use-challenges.ts        β†’ useChallenges(), useJoinChallenge()
    β”œβ”€β”€ use-leaderboard.ts       β†’ useLeaderboard() with pagination
    └── use-users.ts             β†’ useUserProfile(), useSearchUsers()

4.4 Utility Files

File Purpose
api-client.ts Axios instance configured with base URL (localhost:3001/api/v1), auto JWT injection from localStorage, and standardized response types.
constants.ts App-wide constants: language colors (32 languages), tier colors (7 tiers), difficulty colors, rarity colors, navigation items, and the shared ECharts theme.
utils.ts Helper functions including cn() (class name merger using clsx + tailwind-merge).

5. Backend Deep Dive (NestJS)

5.1 Entry Point & Configuration

File Purpose
main.ts Bootstraps the NestJS app. Sets global prefix /api/v1, enables CORS, adds validation pipe, transform interceptor, and Swagger docs at /api/docs.
app.module.ts Root module that imports all 18 feature modules.

5.2 All 18 Backend Modules

backend/src/modules/
β”œβ”€β”€ admin/          β†’ Admin panel endpoints (user management, system stats)
β”œβ”€β”€ analytics/      β†’ Commit analytics, contribution graphs, activity trends
β”œβ”€β”€ auth/           β†’ GitHub OAuth login, JWT token generation & verification
β”œβ”€β”€ badges/         β†’ Badge system (Bronze β†’ Diamond tiers, 5 categories)
β”œβ”€β”€ battles/        β†’ 1v1 developer battles (create, accept, score, winner)
β”œβ”€β”€ challenges/     β†’ Daily/Weekly/Monthly coding challenges with XP rewards
β”œβ”€β”€ compare/        β†’ Developer comparison logic (score calculation)
β”œβ”€β”€ friends/        β†’ Follow/unfollow system, friend suggestions
β”œβ”€β”€ github/         β†’ GitHub API integration via @octokit/rest
β”œβ”€β”€ leaderboards/   β†’ Global rankings by commits, stars, XP, etc.
β”œβ”€β”€ levels/         β†’ Level progression system (Level 1 β†’ ∞)
β”œβ”€β”€ notifications/  β†’ In-app notifications (achievements, battles, friend requests)
β”œβ”€β”€ reports/        β†’ Developer report generation
β”œβ”€β”€ search/         β†’ Full-text search for users and repositories
β”œβ”€β”€ settings/       β†’ User preference management
β”œβ”€β”€ sync/           β†’ GitHub data synchronization service (pulls latest data)
β”œβ”€β”€ users/          β†’ User CRUD, profile management
└── xp/             β†’ Experience Points system (earn XP for activities)

Each module follows the NestJS Module Pattern:

module-name/
β”œβ”€β”€ module-name.module.ts      β†’ Module definition (imports, providers, exports)
β”œβ”€β”€ module-name.controller.ts  β†’ HTTP route handlers (@Get, @Post, @Put, @Delete)
β”œβ”€β”€ module-name.service.ts     β†’ Business logic (injectable service)
└── dto/                       β†’ Data Transfer Objects (request/response shapes)

5.3 Key Backend Services

Service What It Does
AuthService Handles GitHub OAuth flow. Exchanges OAuth code for GitHub access token, fetches user profile, creates/updates user in DB, signs JWT.
SyncService Periodically syncs GitHub data. Uses @octokit/rest to pull repos, commits, PRs, issues, stars, followers, and languages. Stores everything in the database via Prisma.
GithubService Direct GitHub API wrapper. Provides methods like getUser(), getRepos(), getCommitActivity().
XpService Calculates and awards XP for developer activities (commits, PRs, battles won).
LevelsService Determines the user's level based on accumulated XP. Each level requires more XP than the last.
BattlesService Manages 1v1 battles: creation, opponent matching, score calculation, and winner determination.
LeaderboardsService Ranks all developers globally by various metrics (overall rating, commits, stars, XP).
ChallengesService Creates and tracks daily/weekly/monthly challenges. Awards XP on completion.
BadgesService Awards badges based on milestones (e.g., "100 Commits", "First PR Merged").
NotificationsService Creates in-app notifications for achievements, battles, level-ups, and friend requests.

5.4 API Endpoint Prefix

All backend routes are prefixed with /api/v1/:

GET    /api/v1/users/:username
GET    /api/v1/analytics/:username
POST   /api/v1/battles
GET    /api/v1/leaderboards
GET    /api/v1/challenges
PUT    /api/v1/settings
...etc

Swagger documentation is available at: http://localhost:3001/api/docs


6. Database Architecture (PostgreSQL + Prisma)

6.1 Schema Overview

The database has 14 tables managed by Prisma ORM:

erDiagram
    User ||--o{ Repository : "has many"
    User ||--o| DeveloperStats : "has one"
    User ||--o| DeveloperRating : "has one"
    User ||--o{ LanguageStat : "has many"
    User ||--o{ Activity : "has many"
    User ||--o{ Notification : "has many"
    User ||--o{ UserAchievement : "has many"
    User ||--o{ UserBadge : "has many"
    User ||--o{ UserChallenge : "has many"
    User ||--o{ Battle : "challenger/opponent"
    User ||--o{ Follows : "follower/following"
    Challenge ||--o{ UserChallenge : "has many"
    Achievement ||--o{ UserAchievement : "has many"
    Badge ||--o{ UserBadge : "has many"
Loading

6.2 Core Tables

Table Purpose Key Fields
users GitHub developer profiles githubId, username, name, avatar, bio, location, company, website
developer_stats Aggregated coding statistics totalCommits, totalPRs, totalIssues, totalStars, totalForks, streak, longestStreak, avgCommitsPerDay
developer_ratings Gamification ratings overall (score), level, xp, xpToNextLevel, rank, tier (BRONZE→GRANDMASTER), growthScore
repositories User's GitHub repositories name, language, stars, forks, commits, topics[], url
language_stats Language usage breakdown name, percentage, linesOfCode, repos
battles 1v1 developer battles challengerId, opponentId, status, category, challengerScore, opponentScore, winnerId
challenges Coding challenges title, type (DAILY/WEEKLY/MONTHLY), difficulty, xpReward, target, expiresAt
user_challenges User progress on challenges progress, isCompleted, completedAt
achievements Achievement definitions title, rarity (COMMON→LEGENDARY), target, xpReward
user_achievements User's unlocked achievements progress, isUnlocked, unlockedAt
badges Collectible badge definitions name, tier (BRONZE→DIAMOND), category
user_badges User's earned badges earnedAt
activities Activity log/timeline type (COMMIT/PR/ISSUE/REVIEW/STAR/FORK), title, description, repository
notifications In-app notifications type (ACHIEVEMENT/BATTLE/CHALLENGE/FRIEND/SYSTEM/LEVEL_UP), title, message, isRead
follows Social graph (follower/following) followerId, followingId

6.3 Enums

Enum Values
Tier BRONZE, SILVER, GOLD, PLATINUM, DIAMOND, MASTER, GRANDMASTER
ChallengeType DAILY, WEEKLY, MONTHLY, SEASONAL
Difficulty EASY, MEDIUM, HARD, LEGENDARY
Rarity COMMON, RARE, EPIC, LEGENDARY
BadgeTier BRONZE, SILVER, GOLD, PLATINUM, DIAMOND
BattleStatus PENDING, ACTIVE, COMPLETED, CANCELLED
NotificationType ACHIEVEMENT, CHALLENGE, BATTLE, FRIEND, SYSTEM, LEVEL_UP
ActivityType COMMIT, PULL_REQUEST, ISSUE, REVIEW, STAR, FORK, ACHIEVEMENT, LEVEL_UP

7. External APIs & Data Sources

7.1 GitHub REST API (api.github.com)

Endpoint What It Fetches Used In
GET /users/{username} Basic profile: name, avatar, bio, location, followers, public_repos, created_at Compare Page, Profile Page
GET /users/{username}/repos?per_page=100 All repositories: language, stars, forks, topics, description Compare Page (Tech Stack Radar, Language Detection)
GET /search/issues?q=type:pr+author:{username} Total Pull Requests count Compare Page
GET /search/issues?q=type:issue+author:{username} Total Issues count Compare Page
GET /search/commits?q=author:{username} Total Commits count Compare Page
GET /repos/{owner}/{repo}/stats/contributors Per-repo contribution stats: weekly additions, deletions, commits Compare Page (Lines Added/Deleted accuracy)
GET /users/{username}/events/public?per_page=50 Recent public events with timestamps Compare Page (Coding Habit: Night Owl/Early Bird detection)

Note

Rate Limits: Unauthenticated requests are limited to 60/hour per IP. With a GITHUB_TOKEN, this increases to 5,000/hour.

7.2 GitHub Contributions API (github-contributions-api.deno.dev)

Endpoint What It Fetches
GET /{username}.json Full contribution calendar data (365+ days). Used to calculate Current Streak and Peak Streak.

Note

This is a third-party open-source API hosted on Deno Deploy. It scrapes GitHub's contribution graph data and returns it as JSON.

7.3 GitHub API via Octokit (Backend)

The NestJS backend uses @octokit/rest (the official GitHub SDK) for authenticated server-side requests during the Sync process. This provides:

  • Higher rate limits (5,000/hour with token)
  • Access to private repository data (if user grants OAuth scope)
  • Reliable pagination for large data sets

8. Internal API Routes (Next.js Server)

8.1 GitHub Developer Data Proxy

File: route.ts

Endpoint: GET /api/github/developer?username={username}&force={true|false}

What It Does:

  1. Receives a username from the frontend.
  2. Checks if a valid GITHUB_TOKEN exists in .env.local (server-side) OR from the client's Authorization header.
  3. Makes ~8 parallel requests to GitHub's REST API and the Contributions API.
  4. Processes all raw data into a clean DevData object (score, persona, habit, global rank, tech stack, streak, etc.).
  5. Returns the processed JSON to the frontend.

Caching Behavior:

  • Normal requests are cached for 1 hour (revalidate: 3600) using Next.js Data Cache.
  • Each username gets its own cache tag: github-{username}.
  • When ?force=true is passed, revalidateTag() is called, which deletes the old cached data and fetches fresh data from GitHub.

Data Processing Pipeline:

GitHub API β†’ Raw JSON β†’ Process β†’ Score Calculation β†’ Persona Assignment
                                β†’ Coding Habit Detection (time-of-day analysis)
                                β†’ Global Rank Percentile
                                β†’ Tech Stack Detection (framework scanning)
                                β†’ Streak Calculation
                                β†’ Lines of Code Estimation
                                    β†’ Final DevData JSON β†’ Frontend

8.2 Dynamic GitHub Profile SVG Badge Generator

File: src/app/api/badge/[username]/route.ts

Endpoint: GET /api/badge/:username

What It Does:

  1. Fetches developer metrics (Pulse score, global rank, tier/persona, commits, stars, PRs, streak) from the NestJS backend API or GitHub proxy.
  2. Renders an ultra-crisp, dark-themed SVG badge (495x195) with rounded corners, glowing gradient borders, a circular score gauge, and a 2x2 stats grid.
  3. Automatically escapes all XML entities (&, <, >, ", ') to prevent formatting breakage and XSS.
  4. Serves with caching headers: Cache-Control: public, max-age=3600, s-maxage=7200.
  5. Gracefully handles non-existent or invalid usernames with an elegant fallback SVG badge (status 200, SVG content-type), ensuring GitHub README embeds (![CodePulse Badge](...)) always render cleanly through GitHub Camo without broken image icons.

Embed in GitHub README:

[![CodePulse Badge](https://codepulse.dev/api/badge/your-username)](https://codepulse.dev)

9. Authentication Flow

sequenceDiagram
    participant User
    participant Frontend as Next.js Frontend
    participant Backend as NestJS Backend
    participant GitHub as GitHub OAuth

    User->>Frontend: Click "Login with GitHub"
    Frontend->>GitHub: Redirect to github.com/login/oauth/authorize
    GitHub->>Frontend: Redirect back with ?code=xxx
    Frontend->>Backend: POST /api/v1/auth/github (code)
    Backend->>GitHub: Exchange code for access_token
    GitHub-->>Backend: access_token
    Backend->>GitHub: GET /user (with access_token)
    GitHub-->>Backend: User profile data
    Backend->>Backend: Create/Update user in PostgreSQL
    Backend->>Backend: Sign JWT with user data
    Backend-->>Frontend: { token: "eyJhbGciOi..." }
    Frontend->>Frontend: Store JWT in localStorage
    Frontend->>Backend: All subsequent requests include Authorization: Bearer {jwt}
Loading

Key Technologies:

  • Passport.js + passport-jwt strategy on the backend
  • JWT tokens signed by NestJS
  • localStorage on the frontend for token persistence
  • Axios interceptor in api-client.ts for automatic token injection

10. Caching & Performance Architecture

10.1 Multi-Layer Caching & Rate Limiting Strategy

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Layer 1: React Query Client Cache (Browser)      β”‚
β”‚ β€’ staleTime: 60 seconds                          β”‚
β”‚ β€’ Prevents re-fetches on component remounts      β”‚
β”‚ β€’ Automatic background refetch when stale        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Layer 2: Next.js Data Cache (Server Proxy)       β”‚
β”‚ β€’ revalidate: 3600 seconds (1 hour)              β”‚
β”‚ β€’ Tagged by username (github-{username})          β”‚
β”‚ β€’ Invalidated by Refresh button (force=true)     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Layer 3: NestJS Backend Cache & Throttler        β”‚
β”‚ β€’ @nestjs/throttler: 30-60 req/min (IP or User)  β”‚
β”‚ β€’ @nestjs/cache-manager: 5–10 min TTL            β”‚
β”‚ β€’ Invalidation: ?force=true or DELETE /cache/:id β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Layer 4: GitHub API (External)                   β”‚
β”‚ β€’ Rate: 60/hr (no token) or 5,000/hr (with)     β”‚
β”‚ β€’ Real-time data from GitHub                     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

10.2 NestJS GitHub Proxy Routes & Caching Strategy

The NestJS backend provides dedicated cached and rate-limited endpoints for GitHub data under /api/v1/github:

Endpoint Cache Key TTL Rate Limit Description
GET /api/v1/github/developer/:username github:developer:{username} 5 minutes (300s) 30 req/min Aggregated developer metrics (score, habit, persona, stats)
GET /api/v1/github/profile/:username github:profile:{username} 10 minutes (600s) 30 req/min Public GitHub profile metadata
GET /api/v1/github/repos/:username github:repos:{username}:{limit} 5 minutes (300s) 30 req/min Public repository metadata & statistics
GET /api/v1/github/events/:username github:events:{username}:{limit} 3 minutes (180s) 30 req/min Recent public user activity events
DELETE /api/v1/github/cache/:username All user keys N/A 10 req/min Evicts all cached entries for the specified user
POST /api/v1/github/sync github:developer:{username} N/A 10 req/min Busts cache and syncs latest profile data

10.3 Adaptive Rate Limiting (@nestjs/throttler)

  • Authenticated Users: Rate limits are tracked and isolated per authenticated user ID (user-{id}) via JWT tokens.
  • Anonymous / Public Queries: Tracked per client IP address (ip-{ip}), with automatic detection of X-Forwarded-For reverse proxy headers.
  • Protection: Prevents quota exhaustion on upstream GitHub APIs during traffic surges; returns HTTP 429 Too Many Requests when limits are exceeded.

10.4 Cache Invalidation

Trigger What Happens
Normal Request Checks cache β†’ if valid (< TTL), returns cached data instantly with cached: true (0 GitHub API calls).
Refresh / Force (?force=true / ?refresh=true) Evicts the specified cache key β†’ fetches fresh data from GitHub β†’ caches fresh data with TTL.
Purge Endpoint (DELETE /api/v1/github/cache/:username) Clears all cached keys for that developer across developer, profile, repos, and events.
TTL Expiration Cache key automatically expires after 5–10 minutes, ensuring data freshnes without manual intervention.

11. Complete Folder Structure

CodePulse/
β”œβ”€β”€ .env.local                          # Frontend env vars (GITHUB_TOKEN)
β”œβ”€β”€ .gitignore
β”œβ”€β”€ package.json                        # Frontend dependencies
β”œβ”€β”€ next.config.ts                      # Next.js configuration
β”œβ”€β”€ tsconfig.json                       # TypeScript config
β”œβ”€β”€ postcss.config.mjs                  # PostCSS + Tailwind config
β”œβ”€β”€ eslint.config.mjs                   # ESLint config
β”œβ”€β”€ components.json                     # shadcn/ui configuration
β”‚
β”œβ”€β”€ public/                             # Static assets
β”‚
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app/                            # Next.js App Router (Pages)
β”‚   β”‚   β”œβ”€β”€ page.tsx                    # Landing page (3D hero, features)
β”‚   β”‚   β”œβ”€β”€ layout.tsx                  # Root layout (fonts, metadata)
β”‚   β”‚   β”œβ”€β”€ providers.tsx               # React Query + Theme + Toaster
β”‚   β”‚   β”œβ”€β”€ globals.css                 # Tailwind + custom CSS
β”‚   β”‚   β”œβ”€β”€ not-found.tsx               # 404 page
β”‚   β”‚   β”œβ”€β”€ (auth)/                     # Auth pages (no sidebar)
β”‚   β”‚   β”œβ”€β”€ (dashboard)/               # All dashboard pages (with sidebar)
β”‚   β”‚   β”œβ”€β”€ api/github/developer/       # Server-side GitHub proxy
β”‚   β”‚   β”œβ”€β”€ auth/callback/              # OAuth callback
β”‚   β”‚   └── maintenance/                # Maintenance mode
β”‚   β”‚
β”‚   β”œβ”€β”€ components/                     # Reusable React components
β”‚   β”‚   β”œβ”€β”€ animations/                 # Page transitions, animated counters
β”‚   β”‚   β”œβ”€β”€ cards/                      # Stat cards, achievement cards
β”‚   β”‚   β”œβ”€β”€ charts/                     # ECharts: radar, heatmap, bubble, etc.
β”‚   β”‚   β”œβ”€β”€ data-display/              # Activity timeline
β”‚   β”‚   β”œβ”€β”€ feedback/                   # Loading/empty/error states
β”‚   β”‚   β”œβ”€β”€ icons/                      # Custom SVG icons
β”‚   β”‚   β”œβ”€β”€ layout/                     # Sidebar, Topbar, Command Palette
β”‚   β”‚   β”œβ”€β”€ modals/                     # Repo quick-view modal
β”‚   β”‚   β”œβ”€β”€ sections/                   # Landing page 3D hero
β”‚   β”‚   └── ui/                         # 30 shadcn/ui base components
β”‚   β”‚
β”‚   β”œβ”€β”€ hooks/                          # Custom React hooks
β”‚   β”‚   β”œβ”€β”€ use-mobile.ts              # Mobile detection
β”‚   β”‚   └── api/                        # API hooks (React Query)
β”‚   β”‚
β”‚   β”œβ”€β”€ lib/                            # Shared utilities
β”‚   β”‚   β”œβ”€β”€ api-client.ts              # Axios instance (NestJS connection)
β”‚   β”‚   β”œβ”€β”€ constants.ts               # Colors, nav items, chart theme
β”‚   β”‚   β”œβ”€β”€ utils.ts                   # cn() helper, formatters
β”‚   β”‚   └── mock-data/                 # Sample data for development
β”‚   β”‚
β”‚   └── types/                          # Global TypeScript type definitions
β”‚
└── backend/                            # NestJS Backend (separate app)
    β”œβ”€β”€ .env                            # Backend env vars (DB, JWT, GitHub)
    β”œβ”€β”€ package.json                    # Backend dependencies
    β”œβ”€β”€ docker-compose.yml              # PostgreSQL + Redis + Mailpit containers
    β”œβ”€β”€ nest-cli.json                   # NestJS CLI config
    β”œβ”€β”€ tsconfig.json                   # Backend TypeScript config
    β”‚
    β”œβ”€β”€ prisma/
    β”‚   └── schema.prisma               # Database schema (14 tables, 8 enums)
    β”‚
    β”œβ”€β”€ src/
    β”‚   β”œβ”€β”€ main.ts                     # App bootstrap (CORS, Swagger, Validation)
    β”‚   β”œβ”€β”€ app.module.ts               # Root module (imports all 18 modules)
    β”‚   β”œβ”€β”€ app.controller.ts           # Health check endpoint
    β”‚   β”œβ”€β”€ app.service.ts              # App service
    β”‚   β”œβ”€β”€ common/                     # Shared interceptors, guards, pipes
    β”‚   β”œβ”€β”€ prisma/                     # PrismaService (injectable DB client)
    β”‚   └── modules/                    # 18 feature modules (see Section 5.2)
    β”‚
    β”œβ”€β”€ test/                           # E2E test configuration
    β”œβ”€β”€ init.sql                        # Database initialization SQL
    └── dist/                           # Compiled JavaScript output

12. Feature Breakdown

12.1 Landing Page (/)

  • 3D Animated Hero using Three.js + React Three Fiber + Drei
  • Scroll-based animations using GSAP
  • Feature showcase cards with gradient backgrounds
  • "Login with GitHub" CTA button

12.2 Dashboard (/dashboard)

  • Welcome hero banner with personalized greeting
  • Stat cards: commits, PRs, issues, stars, followers, streak
  • Developer Rating card with tier badge (Bronze β†’ Grandmaster)
  • Contribution heatmap (GitHub-style green grid)
  • Commit activity chart (weekly bar chart)
  • Language distribution donut chart
  • Leaderboard preview (top 5 developers)
  • Repository sparklines

12.3 Compare Page (/compare) β€” βš”οΈ The Main Feature

  • Dual search input for any two GitHub usernames
  • Server-side data fetching via /api/github/developer
  • Smart caching (1-hour TTL + manual refresh)
  • User token + Master token support
  • ProfileCard: Avatar, name, bio, location, join date, dev score bar, 4 stats grid
  • Developer Persona: Weekend Warrior / Consistent Coder / Open Source Hero (with icons)
  • Global Percentile Rank: Top 0.1% β†’ Top 50% (with colored badges)
  • Head-to-Head Stats Grid: 10 metrics compared side-by-side (Commits, PRs, Issues, Stars, Followers, Streak, Peak Streak, Repos, Lines Added, Lines Deleted)
  • Animated Progress Bars: Side-by-side comparison with winner highlighting
  • Code Volume Section: Lines Added (green) vs Lines Deleted (red) with Net Impact
  • Developer Skills Radar: 6-axis radar chart (Commits, PRs, Issues, Reviews, Stars, Streak)
  • Tech Stack Radar: Dynamic radar chart showing framework/tool usage across repos
  • Coding Habit: Night Owl πŸŒ™ / Early Bird β˜€οΈ / Evening Coder πŸŒ… / Afternoon Coder β˜• (detected from event timestamps)
  • Recent Comparisons: Saved to localStorage for quick re-runs

12.4 Battles (/battles)

  • Create 1v1 battles with any developer
  • Score calculated from real GitHub stats
  • Battle status: Pending β†’ Active β†’ Completed
  • Winner announcement with animation

12.5 Leaderboard (/leaderboard)

  • Global ranking by overall score
  • Filter by: commits, stars, PRs, XP, streak
  • Tier-based coloring (Bronze through Grandmaster)

12.6 Challenges (/challenges)

  • Daily, Weekly, Monthly, and Seasonal challenges
  • Progress tracking with animated progress bars
  • XP rewards on completion
  • Difficulty levels: Easy β†’ Legendary

12.7 Achievements (/achievements)

  • 100+ unlockable achievements
  • Rarity tiers: Common, Rare, Epic, Legendary
  • Progress tracking per achievement
  • XP bonus on unlock

12.8 Profile (/profile)

  • Personal GitHub data display
  • Repository listing with sparklines
  • Activity timeline
  • Language breakdown
  • Social links

13. Data Flow Diagrams

13.1 Compare Page Data Flow

sequenceDiagram
    participant User as User (Browser)
    participant CP as Compare Page
    participant API as /api/github/developer
    participant Cache as Next.js Data Cache
    participant GH as GitHub API
    participant Contrib as Contributions API

    User->>CP: Enter "user1" vs "user2" β†’ Click Compare
    CP->>API: GET /api/github/developer?username=user1
    CP->>API: GET /api/github/developer?username=user2

    API->>Cache: Check cache for "github-user1"
    alt Cache Hit (< 1 hour old)
        Cache-->>API: Cached DevData
    else Cache Miss
        API->>GH: GET /users/user1
        API->>GH: GET /users/user1/repos
        API->>GH: GET /search/issues?q=type:pr+author:user1
        API->>GH: GET /search/commits?q=author:user1
        API->>GH: GET /users/user1/events/public
        API->>Contrib: GET /user1.json (streak data)
        GH-->>API: Raw data
        Contrib-->>API: Contribution data
        API->>API: Process β†’ Score, Persona, Rank, Habit, TechStack
        API->>Cache: Store with tag "github-user1" (TTL: 1hr)
    end

    API-->>CP: DevData JSON (user1)
    API-->>CP: DevData JSON (user2)
    CP->>CP: Render ProfileCards, Radar Charts, Stats Grid
    CP-->>User: Beautiful comparison UI
Loading

13.2 Refresh (Cache Invalidation) Flow

sequenceDiagram
    participant User as User
    participant CP as Compare Page
    participant API as /api/github/developer
    participant Cache as Next.js Cache

    User->>CP: Click Refresh πŸ”„ Button
    CP->>API: GET /api/github/developer?username=user1&force=true
    API->>Cache: revalidateTag("github-user1") β†’ DELETE old cache
    API->>API: Fetch fresh data from GitHub
    API->>Cache: Store NEW data with tag "github-user1"
    API-->>CP: Fresh DevData JSON
    CP-->>User: Updated stats displayed
Loading

14. Environment Variables

14.1 Frontend (.env.local)

Variable Example Purpose
GITHUB_TOKEN ghp_xxxxxxxxxxxx Server-side GitHub API token for the proxy route. Increases rate limit from 60 to 5,000/hour.
NEXT_PUBLIC_API_URL http://localhost:3001/api/v1 NestJS backend URL for the Axios client.
NEXT_PUBLIC_GITHUB_CLIENT_ID GitHub OAuth App Client ID Enables the GitHub sign-in button.

14.2 Backend (backend/.env)

Variable Example Purpose
DATABASE_URL postgresql://user:pass@host:5432/db PostgreSQL connection string (Prisma).
DIRECT_URL postgresql://user:pass@host:5432/db Direct DB connection (bypasses connection pooler).
GITHUB_CLIENT_ID Iv1.xxxxxxxxxx GitHub OAuth App Client ID.
GITHUB_CLIENT_SECRET xxxxxxxxxxxx GitHub OAuth App Client Secret.
GITHUB_CALLBACK_URL http://localhost:3000/auth/callback OAuth redirect URI.
JWT_SECRET your-secret-key Secret key for signing JWT tokens.
PORT 3001 Backend server port.
APP_URL http://localhost:3000 Public frontend URL used to construct password-reset links.
SMTP_HOST, SMTP_PORT localhost, 1025 SMTP server used for password-reset emails. Defaults to local Mailpit.
SMTP_USER, SMTP_PASSWORD optional SMTP authentication when required by the provider.
SMTP_SECURE false Enables TLS for SMTP when set to true.
MAIL_FROM DevBattle <noreply@example.com> Sender address for reset emails.

Mailpit captures messages locally; it does not deliver them to Gmail or Outlook. To deliver real email, replace the local SMTP values in backend/.env with a provider account:

Gmail (requires 2-Step Verification and a Google App Password; do not use your normal Google password):

SMTP_HOST=smtp.gmail.com
SMTP_PORT=465
SMTP_SECURE=true
SMTP_USER=your-sending-address@gmail.com
SMTP_PASSWORD=your-google-app-password
MAIL_FROM=DevBattle <your-sending-address@gmail.com>

Outlook.com / Microsoft 365:

SMTP_HOST=smtp-mail.outlook.com
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER=your-sending-address@outlook.com
SMTP_PASSWORD=your-mailbox-password-or-provider-app-password
MAIL_FROM=DevBattle <your-sending-address@outlook.com>

After changing backend/.env, restart the backend. APP_URL must be a URL recipients can open; http://localhost:3000 only works for your own machine during local testing. For local testing, keep the Mailpit values and read messages at http://localhost:8025. Never commit SMTP credentials.


15. Deployment Architecture

15.1 Frontend Deployment (Vercel)

Aspect Detail
Platform Vercel (automatic from GitHub pushes)
Build Command next build
Framework Next.js 16.2.9 (auto-detected by Vercel)
Edge Runtime API routes run on Vercel's serverless functions
Cache Next.js Data Cache persisted across deployments
CDN Vercel's global Edge Network for static assets

15.2 Backend Deployment

Aspect Detail
Framework NestJS (Node.js)
Database Supabase PostgreSQL (cloud-hosted)
ORM Prisma (auto-generates migrations)
Docker docker-compose.yml available for local PostgreSQL + Redis

15.3 Infrastructure Diagram

graph TB
    subgraph "Vercel (Frontend)"
        A["Next.js App<br/>SSR + API Routes"]
    end

    subgraph "Cloud (Backend)"
        B["NestJS API<br/>REST + Swagger"]
    end

    subgraph "Supabase"
        C["PostgreSQL<br/>14 Tables"]
    end

    subgraph "External APIs"
        D["GitHub API"]
        E["Contributions API"]
    end

    Users -->|"HTTPS"| A
    A -->|"Axios"| B
    A -->|"Server fetch + Cache"| D
    A -->|"Streak Data"| E
    B -->|"Prisma"| C
    B -->|"Octokit"| D
Loading

16. Development Setup Guide

Step 1: Clone the Repository

git clone https://github.com/code-with-abhi-i5/CodePulse.git
cd CodePulse

Quick Start with Docker (one command)

Requires Docker with Compose v2. From the repository root:

docker compose -f docker-compose.dev.yml up --build
# or: sh scripts/dev-setup.sh   (Windows: scripts\dev-setup.bat)

This starts PostgreSQL 16, Redis 7, Mailpit, the NestJS API and the Next.js app. The backend waits for a healthy database, then runs prisma migrate deploy and prisma db seed before starting, so the database is ready with no manual steps. Both are idempotent: restarting or re-running up will not duplicate data.

  • Frontend: http://localhost:3000, API: http://localhost:3001/api/v1, Swagger: http://localhost:3001/api/docs, Mailpit: http://localhost:8025
  • Source is bind-mounted, so edits hot-reload. Optional secrets (GITHUB_TOKEN, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, JWT_SECRET) are read from a root .env.
  • Stop with docker compose -f docker-compose.dev.yml down; add -v to also wipe the database.
  • Do not run it together with backend/docker-compose.yml (same host ports). The manual steps below are still supported.

Step 2: Install Frontend Dependencies

npm install

Step 3: Install Backend Dependencies

cd backend
npm install

Step 4: Configure Environment Variables

Copy the safe templates with Copy-Item .env.example .env.local and Copy-Item backend/.env.example backend/.env, then fill in your OAuth app and a unique JWT secret. Create /.env.local (frontend):

GITHUB_TOKEN=ghp_your_personal_access_token
NEXT_PUBLIC_API_URL=http://localhost:3001/api/v1
NEXT_PUBLIC_GITHUB_CLIENT_ID=your_github_oauth_client_id

Create /backend/.env (backend):

DATABASE_URL=postgresql://user:password@host:5432/database
DIRECT_URL=postgresql://user:password@host:5432/database
GITHUB_CLIENT_ID=your_github_oauth_client_id
GITHUB_CLIENT_SECRET=your_github_oauth_client_secret
JWT_SECRET=generate_a_long_random_secret
PORT=3001
APP_URL=http://localhost:3000
SMTP_HOST=localhost
SMTP_PORT=1025
SMTP_SECURE=false
MAIL_FROM=DevBattle <noreply@example.com>

For local password-reset email testing, the Docker Compose setup includes Mailpit. Open http://localhost:8025 after starting Docker to view emails. For production, configure SMTP credentials from your email provider and set SMTP_SECURE appropriately. Never commit real credentials.

Step 5: Start PostgreSQL, Redis, and Mailpit

cd backend
docker compose up -d

Step 6: Apply the Database Schema

cd backend
npx prisma generate
npx prisma db push

Step 7: Start the Backend

cd backend
npm run start:dev        # Starts NestJS on port 3001

Step 8: Start the Frontend

# From root directory
npm run dev              # Starts Next.js on port 3000

Step 9: Open the App

Test the Password-Reset Flow

  1. Create an account with email and password at http://localhost:3000/signup.
  2. Visit http://localhost:3000/forgot-password, enter that email, and submit.
  3. For local Mailpit, open http://localhost:8025 and click the reset link. For real delivery, configure Gmail/Outlook SMTP above and check the recipient inbox (including Spam/Junk).
  4. Choose a new password, then sign in with it. A reset link expires after 30 minutes and cannot be reused.
  5. Visiting /dashboard without a valid session redirects to /login.

Tip

This document is a living reference. As new features are added (e.g., Commit Sentiment Analysis, Crown Jewel Matchup), this document should be updated accordingly.


Built with ❀️ by code-with-abhi-i5

About

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages