Skip to content

NaderMohamed325/social_media

Repository files navigation

🚀 Social Media Platform

A sophisticated social media backend platform built with NestJS, featuring real-time notifications, comprehensive API documentation, secure authentication, and scalable architecture designed for high-performance social interactions.


🌟 Key Features

🔐 Authentication & Security

  • Better Auth integration with multiple provider support
  • JWT-based secure authentication with session management
  • Social login (Google, GitHub, Discord) and magic link authentication
  • Role-based access control with comprehensive security middleware
  • Rate limiting, CORS protection, and secure headers

📱 Social Media Core

  • Post management with rich content support and media integration
  • Comment system with threaded discussions and moderation
  • Like/reaction system for posts and comments
  • Advanced filtering, pagination, and search capabilities
  • Media upload and optimization via Cloudinary

🔔 Real-Time Notifications

  • WebSocket-based instant notifications using Socket.IO
  • Redis-powered horizontal scaling and pub/sub messaging
  • BullMQ queue system for reliable notification processing
  • Database persistence for notification history and delivery tracking
  • Type-safe notification system with comprehensive error handling

📊 Scalability & Performance

  • Redis integration for session management and real-time scaling
  • Queue-based processing for heavy operations and background tasks
  • Database optimization with Prisma ORM and connection pooling
  • Horizontal scaling support with Redis adapter for WebSocket clustering

📖 Developer Experience

  • Comprehensive Swagger documentation with detailed API schemas
  • Type-safe development with full TypeScript support
  • Extensive testing capabilities with Jest and e2e testing
  • Modern tooling with ESLint, Prettier, and development workflows

🛠️ Technology Stack

Core Framework & Language

  • NestJS v11 - Progressive Node.js framework with decorators
  • TypeScript - Type-safe JavaScript with advanced features

Authentication & Authorization

  • Better Auth - Modern authentication library
  • JWT tokens with secure session management

Database & ORM

  • PostgreSQL - Production-ready relational database
  • Prisma ORM - Type-safe database toolkit with migrations

Real-Time & Messaging

  • Socket.IO - WebSocket communication for real-time features
  • Redis - In-memory data store for pub/sub and caching
  • BullMQ - Robust queue system for background processing

Media & File Management

  • Cloudinary - Cloud-based media optimization and delivery

Documentation & Development

  • Swagger/OpenAPI - Interactive API documentation
  • Jest - Testing framework with comprehensive coverage

🏗️ Architecture Overview

Notification System Flow

  1. Action Trigger → User performs action (like, comment, etc.)
  2. Queue Processing → BullMQ queues notification job for reliability
  3. Database Persistence → Notification record stored in PostgreSQL
  4. Real-Time Delivery → WebSocket broadcasts to connected users
  5. Scaling → Redis adapter enables multi-instance WebSocket distribution

Authentication Flow

  1. Registration/Login → Better Auth handles multiple authentication methods
  2. Token Generation → Secure JWT tokens with refresh capabilities
  3. Request Authorization → Guards validate tokens on protected endpoints
  4. Session Management → Redis-backed session storage for scalability

📁 Project Structure

src/
├── app.module.ts              # Root application module with all integrations
├── main.ts                   # Application bootstrap with Swagger configuration
├── auth.ts                   # Better Auth configuration and providers
├── envVariables.ts           # Environment variable validation and types
├── common/                   # Shared utilities and configurations
│   ├── configs/             # Configuration files (Cloudinary, Redis)
│   ├── decorators/          # Custom decorators for API documentation
│   ├── guards/              # Authentication and authorization guards
│   └── interceptors/        # Request/response interceptors and logging
├── post/                    # Post management with full CRUD operations
│   ├── post.controller.ts   # REST endpoints with comprehensive Swagger docs
│   ├── post.service.ts      # Business logic and database operations
│   ├── post.module.ts       # Module configuration and dependencies
│   └── dto/                # Data transfer objects with validation
├── comment/                 # Comment system with notification integration
│   ├── comment.controller.ts # Comment API endpoints
│   ├── comment.service.ts   # Comment business logic
│   └── dto/                # Comment DTOs and validation schemas
├── like/                   # Like/reaction system
│   ├── like.controller.ts  # Like management endpoints
│   ├── like.service.ts     # Like business logic with notifications
│   └── dto/               # Like-related data structures
├── notification/           # Real-time notification system
│   ├── notification.gateway.ts    # WebSocket gateway with Redis scaling
│   ├── notification.processor.ts  # Queue job processing
│   ├── notification.service.ts    # Notification queue management
│   ├── notification.module.ts     # Module with all dependencies
│   └── dto/                       # Notification DTOs and types
├── prisma/                # Database service and configuration
│   ├── prisma.service.ts  # Database connection and query methods
│   └── prisma.module.ts   # Prisma module for dependency injection
└── redis/                 # Redis service for caching and pub/sub
    ├── redis.service.ts   # Redis connection and operations
    └── redis.module.ts    # Redis module configuration

prisma/
├── schema.prisma          # Database schema with all models
├── migrations/           # Database migration history
└── dev.db               # Development database file

🌐 API Documentation

Interactive Documentation

  • Swagger UI: http://localhost:3000/api - Full interactive API explorer
  • OpenAPI JSON: http://localhost:3000/api-json - Machine-readable API schema

Authentication Endpoints (Better Auth)

  • POST /api/auth/sign-up - User registration with validation
  • POST /api/auth/sign-in - Multi-method user authentication
  • POST /api/auth/sign-out - Secure user logout
  • GET /api/auth/session - Current session information
  • POST /api/auth/forgot-password - Password reset initiation
  • POST /api/auth/reset-password - Password reset completion

Social Media Endpoints

Posts Management

  • GET /api/posts - List posts with advanced filtering and pagination
  • GET /api/posts/:id - Detailed post information with engagement metrics
  • POST /api/posts - Create new post with media upload support
  • PATCH /api/posts/:id - Update post content and settings
  • DELETE /api/posts/:id - Delete post with cascade handling

Comments System

  • GET /api/comments - List comments with threading support
  • GET /api/comments/:id - Detailed comment information
  • POST /api/comments - Create comment with notification triggering
  • PATCH /api/comments/:id - Update comment content
  • DELETE /api/comments/:id - Delete comment with cleanup

Likes & Reactions

  • POST /api/likes/post/:postId - Like/unlike posts with real-time updates
  • POST /api/likes/comment/:commentId - Like/unlike comments
  • GET /api/likes/post/:postId - Get post like statistics
  • GET /api/likes/user/:userId - Get user's like activity

Notifications (Real-Time)

  • WebSocket Events: notification:new, notification:read, notification:delete
  • REST Endpoints: GET /api/notifications, PATCH /api/notifications/:id/read

🛡️ Security & Performance Features

Security Implementations

  • Authentication Guards protecting all sensitive endpoints
  • Rate Limiting with configurable thresholds per endpoint
  • CORS Protection with whitelist-based origin validation
  • Input Validation using class-validator with comprehensive DTOs
  • SQL Injection Protection via Prisma ORM parameterized queries
  • XSS Protection with built-in NestJS sanitization
  • Secure Headers middleware for production deployment
  • Environment-based Configuration with validation schemas

Performance Optimizations

  • Redis Caching for frequently accessed data
  • Database Connection Pooling for optimal resource usage
  • Queue-based Processing for heavy operations
  • WebSocket Scaling with Redis adapter for multi-instance deployment
  • Efficient Pagination with cursor-based and offset strategies
  • Image Optimization via Cloudinary transformations

🚀 Getting Started

Prerequisites

  • Node.js (v18 or higher)
  • PostgreSQL (v13 or higher)
  • Redis (v6 or higher)
  • Cloudinary account for media management

Quick Setup

  1. Clone and Install

    git clone  https://github.com/NaderMohamed325/social_media
    cd social-media-platform
    pnpm install  # or npm install / yarn install
  2. Environment Configuration

    cp .env.example .env

    Configure your .env file with:

    # Database
    DATABASE_URL="postgresql://user:password@localhost:5432/social_media"
    
    # Redis
    REDIS_HOST="localhost"
    REDIS_PORT=6379
    REDIS_PASSWORD="" # if required
    
    # Better Auth
    BETTER_AUTH_SECRET="your-secret-key"
    BETTER_AUTH_URL="http://localhost:3000"
    
    # Cloudinary
    CLOUDINARY_CLOUD_NAME="your-cloud-name"
    CLOUDINARY_API_KEY="your-api-key"
    CLOUDINARY_API_SECRET="your-api-secret"
    
    # Application
    PORT=3000
    NODE_ENV="development"
  3. Database Setup

    npx prisma migrate dev --name init
    npx prisma generate
  4. Start Development Server

    pnpm run start:dev

🔧 Development Commands

# Development
pnpm run start:dev          # Start with hot reload
pnpm run start:debug        # Start with debugger
pnpm run start:prod         # Production mode

# Testing
pnpm run test              # Unit tests
pnpm run test:e2e          # End-to-end tests
pnpm run test:cov          # Test coverage

# Database
npx prisma studio          # Database browser
npx prisma migrate dev     # Create and apply migration
npx prisma generate        # Generate Prisma client

# Code Quality
pnpm run lint             # ESLint checking
pnpm run format           # Prettier formatting

📊 Monitoring & Deployment

Health Checks

  • Application health endpoint at /health
  • Database connection monitoring
  • Redis connectivity validation
  • Queue system status tracking

Production Considerations

  • Environment Variables: Secure secret management
  • Database Migrations: Automated deployment pipelines
  • Redis Clustering: High availability configuration
  • Load Balancing: Multi-instance WebSocket scaling
  • Logging: Comprehensive application and error logging
  • Monitoring: Performance metrics and alerting

📞 Support & Development

Documentation Resources

  • API Documentation: http://localhost:3000/api (Swagger UI)
  • Database Schema: Prisma Studio for visual database exploration
  • Architecture Diagrams: Located in /docs directory

Development Support

  • Code Standards: ESLint + Prettier configuration included
  • Testing: Comprehensive Jest setup with e2e testing capabilities
  • Debugging: VS Code debug configuration provided
  • Git Hooks: Pre-commit hooks for code quality assurance

Contact Information

  • Technical Support: Create GitHub issues for bugs and feature requests
  • Documentation: Comprehensive inline code documentation and Swagger specs
  • Community: Join discussions in repository discussions section

📄 License & Contributing

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing: We welcome contributions! Please read our contributing guidelines and code of conduct before submitting pull requests.


🎯 Roadmap & Future Enhancements

  • Advanced Analytics: User engagement and content performance metrics
  • Content Moderation: AI-powered content filtering and moderation tools
  • Mobile API: Optimized endpoints for mobile applications
  • Microservices: Service decomposition for larger scale deployments
  • GraphQL: Alternative API interface alongside REST endpoints

About

A NestJS backend for a social media platform with Better Auth for authentication (Google, JWT, cookies), role-based access (admin/user), and Cloudinary-powered media uploads.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors