Skip to content

A high-performance, real-time leaderboard system built with Node.js, Express, PostgreSQL, Redis, and Socket.IO. Features include user authentication, game management, score tracking, live leaderboards, and direct messaging.

Notifications You must be signed in to change notification settings

sugamghising/Real-time-Leaderboard

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

17 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐ŸŽฎ Real-Time Leaderboard

A complete full-stack real-time leaderboard system built with modern web technologies. Features user authentication, game management, score tracking, live leaderboards, direct messaging, and social features.

๐Ÿš€ Features

Core Functionality

  • โœ… JWT Authentication - Secure access & refresh token rotation
  • โœ… Role-Based Access Control - User/Admin permissions
  • โœ… Game Management - CRUD operations with image uploads
  • โœ… Score Submission - Real-time score tracking with metadata
  • โœ… Live Leaderboards - Global, per-game, and daily rankings
  • โœ… Direct Messaging - Real-time chat with unread tracking
  • โœ… Social Features - Friend requests, user connections
  • โœ… WebSocket Support - Live updates via Socket.IO
  • โœ… Responsive UI - Modern React interface with Tailwind CSS

Tech Stack

Backend

  • Runtime: Node.js with TypeScript
  • Framework: Express 5.1
  • Database: PostgreSQL (via Prisma ORM)
  • Cache: Redis 5.9
  • Real-time: Socket.IO 4.8
  • Validation: Zod
  • Auth: JWT (jsonwebtoken)
  • File Upload: Multer + Cloudinary
  • Security: bcrypt password hashing

Frontend

  • Framework: React 18 with TypeScript
  • Build Tool: Vite
  • State Management: Zustand
  • Data Fetching: TanStack Query (React Query)
  • Styling: Tailwind CSS
  • Forms: React Hook Form + Zod
  • Real-time: Socket.IO Client
  • Icons: Lucide React
  • Animations: Framer Motion

๐Ÿ“‹ Prerequisites

  • Node.js >= 18.x
  • PostgreSQL >= 14.x
  • Redis >= 6.x
  • Cloudinary account (for image uploads)

๐Ÿ› ๏ธ Installation

1. Clone & Install Dependencies

# Install backend dependencies
cd server
npm install

# Install frontend dependencies
cd ../client
npm install

# Return to root
cd ..

2. Environment Setup

Create a .env file in the server/ directory:

# Server
PORT=5000
NODE_ENV=development

# Database (PostgreSQL)
DATABASE_URL="postgresql://user:password@localhost:5432/leaderboard?schema=public"

# Redis
REDIS_URL="redis://localhost:6379"

# JWT Secrets
JWT_SECRET="your-super-secret-jwt-key-here"
JWT_REFRESH_TOKEN_SECRET="your-refresh-token-secret-here"

# Cloudinary (for image uploads)
CLOUDINARY_CLOUD_NAME="your-cloud-name"
CLOUDINARY_API_KEY="your-api-key"
CLOUDINARY_API_SECRET="your-api-secret"

3. Database Setup

cd server

# Generate Prisma Client
npx prisma generate

# Run migrations
npx prisma migrate dev

# (Optional) Open Prisma Studio
npx prisma studio

4. Start Development Servers

# Terminal 1: Start Backend Server
cd server
npm run dev
# Server will start on http://localhost:5000

# Terminal 2: Start Frontend Client
cd client
npm run dev
# Client will start on http://localhost:5173 (or next available port)

5. Access the Application

Open your browser and navigate to http://localhost:5173 to access the full application.


๐Ÿ“ก API Endpoints

Authentication

POST   /v1/api/auth/register          - Register new user
POST   /v1/api/auth/login             - Login (returns access + refresh tokens)
POST   /v1/api/auth/refresh           - Refresh access token
POST   /v1/api/auth/logout            - Logout (revoke refresh token)

Users

GET    /v1/api/users                  - Get all users (auth required)
GET    /v1/api/users/:id              - Get user by ID (auth required)
PUT    /v1/api/users/:id              - Update user (own profile or admin)
DELETE /v1/api/users/:id              - Delete user (own profile or admin)

Games

GET    /v1/api/games                  - Get all games (public)
GET    /v1/api/games/:id              - Get game details (public)
POST   /v1/api/games                  - Create game (admin only, supports image)
PUT    /v1/api/games/:id              - Update game (admin only, supports image)
DELETE /v1/api/games/:id              - Delete game (admin only)

Scores

POST   /v1/api/scores/:id             - Submit score for game (auth required)
GET    /v1/api/scores/:id/best        - Get user's best score (auth required)

Leaderboards

GET    /v1/api/leaderboard/global                - Global leaderboard
GET    /v1/api/leaderboard/game/:id              - Game-specific leaderboard
GET    /v1/api/leaderboard/game/:id/daily        - Daily leaderboard
GET    /v1/api/leaderboard/game/:id/rank         - User's rank (auth required)

Query params: ?limit=100 (default: 100)

Messages

POST   /v1/api/messages/                         - Send message (auth required)
GET    /v1/api/messages/conversation/:id         - Get conversation (auth required)
POST   /v1/api/messages/mark-read                - Mark messages as read (auth required)
GET    /v1/api/messages/unread-count             - Get unread count (auth required)

๐Ÿ”Œ WebSocket Events

Client โ†’ Server

socket.emit("joinGameRoom", gameId); // Join game room for updates
socket.emit("leaveGameRoom", gameId); // Leave game room

Server โ†’ Client

socket.on("leaderboard:update", (data) => {
  // { gameId, userId, score, rank }
});

socket.on("message:new", (message) => {
  // New message received
});

socket.on("message:sent", (message) => {
  // Message sent confirmation
});

socket.on("message:unread_count", ({ count }) => {
  // Updated unread message count
});

Socket Authentication

const socket = io("http://localhost:5000", {
  auth: {
    token: "your-jwt-access-token",
  },
});

๐Ÿ“ฆ Request Examples

Register User

POST /v1/api/auth/register
Content-Type: application/json

{
  "username": "player123",
  "email": "player@example.com",
  "password": "securePassword123"
}

Login

POST /v1/api/auth/login
Content-Type: application/json

{
  "email": "player@example.com",
  "password": "securePassword123"
}

# Response:
{
  "message": "Login Successful",
  "accessToken": "eyJhbGc...",
  "refreshToken": "eyJhbGc...",
  "user": {
    "userId": "uuid",
    "name": "player123",
    "email": "player@example.com",
    "role": "USER"
  }
}

Create Game (Admin)

POST /v1/api/games
Authorization: Bearer <admin-access-token>
Content-Type: multipart/form-data

slug: tetris-classic
title: Tetris Classic
description: Classic block-stacking puzzle game
metadata: {"maxLevel": 20, "scoreMultiplier": 100}
image: <file>

Submit Score

POST /v1/api/scores/:gameId
Authorization: Bearer <access-token>
Content-Type: application/json

{
  "score": 15000,
  "meta": {
    "level": 10,
    "lines": 45,
    "duration": 320
  }
}

# Response:
{
  "success": true,
  "saved": { /* score object */ },
  "leaderboardUpdated": true,
  "rank": 3,
  "score": 15000
}

Get Leaderboard

GET /v1/api/leaderboard/game/:gameId?limit=50

# Response:
[
  {
    "rank": 1,
    "userId": "uuid",
    "score": 25000,
    "user": {
      "id": "uuid",
      "username": "topplayer",
      "displayName": "Top Player",
      "avatarUrl": "https://..."
    }
  },
  ...
]

Send Message

POST /v1/api/messages
Authorization: Bearer <access-token>
Content-Type: application/json

{
  "toUserId": "recipient-uuid",
  "content": "Hello! Good game!"
}

๐ŸŽจ Frontend Features

User Interface

  • Responsive Design - Mobile-first approach with Tailwind CSS
  • Modern UI Components - Clean, accessible interface
  • Real-time Updates - Live leaderboard and message updates
  • Form Validation - Client-side validation with error handling
  • Loading States - Smooth loading indicators and skeletons

Pages & Features

Authentication

  • User registration and login
  • Form validation and error handling
  • Secure token management

Dashboard

  • User statistics and overview
  • Quick action cards
  • Top players preview

Games

  • Browse available games
  • Game details with leaderboard preview
  • Score submission with metadata support

Leaderboards

  • Global leaderboard rankings
  • Game-specific leaderboards
  • Real-time rank updates
  • Daily leaderboard support

Social Features

  • Friend requests (send, accept, reject)
  • Friends list management
  • Real-time messaging system
  • Unread message counters

Admin Panel

  • Game management (CRUD operations)
  • User statistics overview
  • Admin-only features

๐Ÿ”Œ WebSocket Events

๐Ÿ—„๏ธ Database Schema

Key Models

  • User - Authentication, profile, roles
  • Game - Game definitions with metadata
  • Score - User scores per game
  • Message - Direct messages between users
  • RefreshToken - JWT refresh token management
  • Friendship - Social connections
  • Leaderboard - Cached in Redis sorted sets

Indexes

Optimized queries with composite indexes on:

  • Score: [gameId, createdAt], [userId]
  • Message: [toUserId, isRead], [fromUserId, createdAt], [toUserId, createdAt]

๐Ÿ” Security Features

  • โœ… Password hashing with bcrypt (10 rounds)
  • โœ… JWT access tokens (1h expiry)
  • โœ… Refresh token rotation (2d expiry)
  • โœ… Token revocation on logout
  • โœ… Role-based authorization
  • โœ… Input validation with Zod
  • โœ… SQL injection protection (Prisma)
  • โœ… CORS configuration

๐Ÿ—๏ธ Project Structure

.
โ”œโ”€โ”€ client/                    # React Frontend
โ”‚   โ”œโ”€โ”€ public/               # Static assets
โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”œโ”€โ”€ api/             # API endpoints & axios config
โ”‚   โ”‚   โ”œโ”€โ”€ components/      # Reusable UI components
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ common/     # Basic components (Button, Input, etc.)
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ features/   # Feature-specific components
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ layout/     # Layout components
โ”‚   โ”‚   โ”œโ”€โ”€ contexts/       # React contexts (legacy)
โ”‚   โ”‚   โ”œโ”€โ”€ hooks/          # Custom React hooks
โ”‚   โ”‚   โ”œโ”€โ”€ lib/            # Utilities (queryClient, utils)
โ”‚   โ”‚   โ”œโ”€โ”€ pages/          # Page components
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ auth/       # Authentication pages
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ dashboard/  # Dashboard pages
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ games/      # Game-related pages
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ leaderboard/ # Leaderboard pages
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ chat/       # Chat pages
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ friends/    # Friends pages
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ profile/    # Profile pages
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ admin/      # Admin pages
โ”‚   โ”‚   โ”œโ”€โ”€ providers/      # Context providers
โ”‚   โ”‚   โ”œโ”€โ”€ stores/         # Zustand stores
โ”‚   โ”‚   โ”œโ”€โ”€ styles/         # Global styles
โ”‚   โ”‚   โ”œโ”€โ”€ types/          # TypeScript type definitions
โ”‚   โ”‚   โ””โ”€โ”€ utils/          # Helper functions
โ”‚   โ”œโ”€โ”€ package.json
โ”‚   โ”œโ”€โ”€ tsconfig.json
โ”‚   โ”œโ”€โ”€ vite.config.ts
โ”‚   โ””โ”€โ”€ README.md
โ”œโ”€โ”€ server/                    # Node.js Backend
โ”‚   โ”œโ”€โ”€ prisma/
โ”‚   โ”‚   โ”œโ”€โ”€ schema.prisma    # Database schema
โ”‚   โ”‚   โ””โ”€โ”€ migrations/      # Migration history
โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”œโ”€โ”€ config/         # Configuration files
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ db.ts       # Prisma client
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ redis.ts    # Redis client
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ cloudinary.ts # Cloudinary config
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ socket.ts   # Socket.IO setup
โ”‚   โ”‚   โ”œโ”€โ”€ controllers/    # Request handlers
โ”‚   โ”‚   โ”œโ”€โ”€ middleware/     # Auth & role middleware
โ”‚   โ”‚   โ”œโ”€โ”€ routes/        # API route definitions
โ”‚   โ”‚   โ”œโ”€โ”€ schemas/       # Zod validation schemas
โ”‚   โ”‚   โ”œโ”€โ”€ services/      # Business logic
โ”‚   โ”‚   โ”œโ”€โ”€ types/         # TypeScript types
โ”‚   โ”‚   โ”œโ”€โ”€ utils/         # Helper functions
โ”‚   โ”‚   โ””โ”€โ”€ index.ts       # App entry point
โ”‚   โ”œโ”€โ”€ .env               # Environment variables
โ”‚   โ”œโ”€โ”€ package.json
โ”‚   โ”œโ”€โ”€ tsconfig.json
โ”‚   โ””โ”€โ”€ README.md
โ””โ”€โ”€ README.md               # This file

๐Ÿš€ Deployment

Backend Production Build

cd server
npm run build
npm start

Frontend Production Build

cd client
npm run build
# Dist files will be in client/dist/

Environment Variables (Production)

  • Set NODE_ENV=production
  • Use secure JWT secrets (32+ characters)
  • Configure production database URL
  • Enable Redis persistence
  • Set up CORS allowed origins
  • Use managed Cloudinary account

Recommended Services

  • Database: Railway, Neon, Supabase
  • Redis: Redis Cloud, Upstash
  • Backend Hosting: Railway, Render, Fly.io
  • Frontend Hosting: Vercel, Netlify, Railway
  • CDN: Cloudinary (images)

๐Ÿ“Š Performance Features

  • Redis Caching - Leaderboard data in sorted sets
  • Database Indexes - Optimized query performance
  • Connection Pooling - Prisma connection management
  • Pagination - Cursor-based for messages, limit-based for leaderboards
  • WebSocket - Efficient real-time updates

๐Ÿงช Testing

Manual Testing

  1. Backend Setup:

    • Register user โ†’ Login โ†’ Get tokens
    • Create admin user in DB: UPDATE "User" SET role = 'ADMIN' WHERE email = '...'
    • Create games with admin token
    • Submit scores and verify leaderboard updates
  2. Frontend Testing:

    • Register/login through the UI
    • Browse games and submit scores
    • Check real-time leaderboard updates
    • Test friend requests and messaging
    • Verify responsive design on mobile/desktop
  3. Real-time Features:

    • Test Socket.IO connections
    • Open multiple browser tabs to verify live updates
    • Test message delivery and friend request notifications

Example Admin Promotion

UPDATE "User" SET role = 'ADMIN' WHERE email = 'admin@example.com';

๐Ÿ› Common Issues

Prisma Client Not Generated

npx prisma generate

Redis Connection Error

Ensure Redis is running:

redis-server
# or
docker run -d -p 6379:6379 redis

Database Migration Issues

npx prisma migrate reset  # โš ๏ธ Drops all data
npx prisma migrate dev

Port Already in Use

Change PORT in .env or kill process:

# Windows
netstat -ano | findstr :5000
taskkill /PID <PID> /F

# Linux/Mac
lsof -ti:5000 | xargs kill -9

๐Ÿ“ Scripts

Backend Scripts (server/)

{
  "start": "node dist/index.js",
  "build": "tsc",
  "dev": "nodemon --watch src --ext ts --exec \"npm run build && npm run start\"",
  "postinstall": "prisma generate"
}

Frontend Scripts (client/)

{
  "dev": "vite",
  "build": "tsc -b && vite build",
  "preview": "vite preview"
}

๐Ÿค Contributing

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

๐Ÿ“„ License

ISC


๐Ÿ‘จโ€๐Ÿ’ป Author

Built with โค๏ธ for real-time gaming experiences - Full-stack application with modern React frontend and robust Node.js backend.


๐Ÿ”— Resources

Backend

Frontend


Happy Coding! ๐ŸŽฎ๐Ÿš€

About

A high-performance, real-time leaderboard system built with Node.js, Express, PostgreSQL, Redis, and Socket.IO. Features include user authentication, game management, score tracking, live leaderboards, and direct messaging.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages