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.
- 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
- 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
- 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
- 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
- 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
- NestJS v11 - Progressive Node.js framework with decorators
- TypeScript - Type-safe JavaScript with advanced features
- Better Auth - Modern authentication library
- JWT tokens with secure session management
- PostgreSQL - Production-ready relational database
- Prisma ORM - Type-safe database toolkit with migrations
- 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
- Cloudinary - Cloud-based media optimization and delivery
- Swagger/OpenAPI - Interactive API documentation
- Jest - Testing framework with comprehensive coverage
- Action Trigger → User performs action (like, comment, etc.)
- Queue Processing → BullMQ queues notification job for reliability
- Database Persistence → Notification record stored in PostgreSQL
- Real-Time Delivery → WebSocket broadcasts to connected users
- Scaling → Redis adapter enables multi-instance WebSocket distribution
- Registration/Login → Better Auth handles multiple authentication methods
- Token Generation → Secure JWT tokens with refresh capabilities
- Request Authorization → Guards validate tokens on protected endpoints
- Session Management → Redis-backed session storage for scalability
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
- Swagger UI:
http://localhost:3000/api- Full interactive API explorer - OpenAPI JSON:
http://localhost:3000/api-json- Machine-readable API schema
POST /api/auth/sign-up- User registration with validationPOST /api/auth/sign-in- Multi-method user authenticationPOST /api/auth/sign-out- Secure user logoutGET /api/auth/session- Current session informationPOST /api/auth/forgot-password- Password reset initiationPOST /api/auth/reset-password- Password reset completion
GET /api/posts- List posts with advanced filtering and paginationGET /api/posts/:id- Detailed post information with engagement metricsPOST /api/posts- Create new post with media upload supportPATCH /api/posts/:id- Update post content and settingsDELETE /api/posts/:id- Delete post with cascade handling
GET /api/comments- List comments with threading supportGET /api/comments/:id- Detailed comment informationPOST /api/comments- Create comment with notification triggeringPATCH /api/comments/:id- Update comment contentDELETE /api/comments/:id- Delete comment with cleanup
POST /api/likes/post/:postId- Like/unlike posts with real-time updatesPOST /api/likes/comment/:commentId- Like/unlike commentsGET /api/likes/post/:postId- Get post like statisticsGET /api/likes/user/:userId- Get user's like activity
- WebSocket Events:
notification:new,notification:read,notification:delete - REST Endpoints:
GET /api/notifications,PATCH /api/notifications/:id/read
- 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
- 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
- Node.js (v18 or higher)
- PostgreSQL (v13 or higher)
- Redis (v6 or higher)
- Cloudinary account for media management
-
Clone and Install
git clone https://github.com/NaderMohamed325/social_media cd social-media-platform pnpm install # or npm install / yarn install
-
Environment Configuration
cp .env.example .env
Configure your
.envfile 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"
-
Database Setup
npx prisma migrate dev --name init npx prisma generate
-
Start Development Server
pnpm run start:dev
# 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- Application health endpoint at
/health - Database connection monitoring
- Redis connectivity validation
- Queue system status tracking
- 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
- API Documentation:
http://localhost:3000/api(Swagger UI) - Database Schema: Prisma Studio for visual database exploration
- Architecture Diagrams: Located in
/docsdirectory
- 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
- 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
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.
- 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