π 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
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 π» Contributor π¨ 390 commits |
@Babin123456 π» Contributor π¨ 120 commits |
@pratikadamas π Maintainer π¨ 90 commits |
@divyanshAgarwal123 π» Contributor π¨ 31 commits |
@Itssonia7 π» Contributor π¨ 20 commits |
@Sarbajit-Sengupta π» Contributor π¨ 11 commits |
|
@Trunal2005 π» Contributor π¨ 7 commits |
@aush5895 π» Contributor π¨ 6 commits |
@nilesh0199 π» Contributor π¨ 6 commits |
@Ankit-Kum-ar π» Contributor π¨ 5 commits |
@bhavyasingh-sa π» Contributor π¨ 5 commits |
@shahkhushi0307 π» Contributor π¨ 3 commits |
|
@sumittiwari1302 π» Contributor π¨ 2 commits |
@chanchall26 π» Contributor π¨ 2 commits |
@tesfa27 π» Contributor π¨ 1 commits |
@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! π
| 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 readCONTRIBUTING.mdbefore starting!
Version: 1.0 | Last Updated: July 2026
Author: code-with-abhi-i5 | Repository: CodePulse on GitHub
- Project Overview
- High-Level Architecture
- Technology Stack β Complete Breakdown
- Frontend Deep Dive (Next.js)
- Backend Deep Dive (NestJS)
- Database Architecture (PostgreSQL + Prisma)
- External APIs & Data Sources
- Internal API Routes (Next.js Server)
- Authentication Flow
- Caching & Performance Architecture
- Complete Folder Structure
- Feature Breakdown
- Data Flow Diagrams
- Environment Variables
- Deployment Architecture
- Development Setup Guide
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.
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
| 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 |
| 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. |
| 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. |
| 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. |
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
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
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()
| 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). |
| 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. |
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)
| 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. |
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
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"
| 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 |
| 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 |
| 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.
| 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.
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
File: route.ts
Endpoint: GET /api/github/developer?username={username}&force={true|false}
What It Does:
- Receives a username from the frontend.
- Checks if a valid
GITHUB_TOKENexists in.env.local(server-side) OR from the client'sAuthorizationheader. - Makes ~8 parallel requests to GitHub's REST API and the Contributions API.
- Processes all raw data into a clean
DevDataobject (score, persona, habit, global rank, tech stack, streak, etc.). - 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=trueis 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
File: src/app/api/badge/[username]/route.ts
Endpoint: GET /api/badge/:username
What It Does:
- Fetches developer metrics (Pulse score, global rank, tier/persona, commits, stars, PRs, streak) from the NestJS backend API or GitHub proxy.
- Renders an ultra-crisp, dark-themed SVG badge (
495x195) with rounded corners, glowing gradient borders, a circular score gauge, and a 2x2 stats grid. - Automatically escapes all XML entities (
&,<,>,",') to prevent formatting breakage and XSS. - Serves with caching headers:
Cache-Control: public, max-age=3600, s-maxage=7200. - Gracefully handles non-existent or invalid usernames with an elegant fallback SVG badge (status 200, SVG content-type), ensuring GitHub README embeds (
) always render cleanly through GitHub Camo without broken image icons.
Embed in GitHub README:
[](https://codepulse.dev)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}
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.tsfor automatic token injection
ββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 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 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββ
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 |
- 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 ofX-Forwarded-Forreverse proxy headers. - Protection: Prevents quota exhaustion on upstream GitHub APIs during traffic surges; returns
HTTP 429 Too Many Requestswhen limits are exceeded.
| 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. |
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
- 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
- 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
- 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
- Create 1v1 battles with any developer
- Score calculated from real GitHub stats
- Battle status: Pending β Active β Completed
- Winner announcement with animation
- Global ranking by overall score
- Filter by: commits, stars, PRs, XP, streak
- Tier-based coloring (Bronze through Grandmaster)
- Daily, Weekly, Monthly, and Seasonal challenges
- Progress tracking with animated progress bars
- XP rewards on completion
- Difficulty levels: Easy β Legendary
- 100+ unlockable achievements
- Rarity tiers: Common, Rare, Epic, Legendary
- Progress tracking per achievement
- XP bonus on unlock
- Personal GitHub data display
- Repository listing with sparklines
- Activity timeline
- Language breakdown
- Social links
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
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
| 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. |
| 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.
| 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 |
| 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 |
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
git clone https://github.com/code-with-abhi-i5/CodePulse.git
cd CodePulseRequires 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-vto also wipe the database. - Do not run it together with
backend/docker-compose.yml(same host ports). The manual steps below are still supported.
npm installcd backend
npm installCopy 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_idCreate /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.
cd backend
docker compose up -dcd backend
npx prisma generate
npx prisma db pushcd backend
npm run start:dev # Starts NestJS on port 3001# From root directory
npm run dev # Starts Next.js on port 3000- Frontend: http://localhost:3000
- Backend API: http://localhost:3001/api/v1
- Swagger Docs: http://localhost:3001/api/docs
- Create an account with email and password at
http://localhost:3000/signup. - Visit
http://localhost:3000/forgot-password, enter that email, and submit. - For local Mailpit, open
http://localhost:8025and click the reset link. For real delivery, configure Gmail/Outlook SMTP above and check the recipient inbox (including Spam/Junk). - Choose a new password, then sign in with it. A reset link expires after 30 minutes and cannot be reused.
- Visiting
/dashboardwithout 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