App Link
Introduction
This document provides a comprehensive overview of the Dancely backend system, a RESTful API server for a video streaming platform with social networking capabilities. Dancely enables users to upload, manage, and share dance videos while engaging through likes, comments, follows, and community posts. The platform implements a complete authentication system, media storage integration, and real-time social interaction features.
System Capabilities
Dancely provides a comprehensive suite of features organized into distinct functional domains:
Domain | Capabilities | Primary Routes |
|---|---|---|
Authentication | User registration, email verification, login/logout, password reset, token refresh |
|
User Management | Profile management, bio updates, avatar/cover image, user search, watch history |
|
Video Platform | Video upload (MP4), thumbnail management, CRUD operations, view tracking, publishing control |
|
Social Engagement | Like/unlike videos/comments/posts, toggle-based interaction |
|
Comments | Comment on videos and community posts, CRUD operations, ownership validation |
|
Followers | Follow/unfollow users, retrieve follower/following lists with pagination |
|
Community | Create and manage text-based posts, community feed aggregation |
|
Playlists | Create video collections, add/remove videos, playlist management |
|
Analytics | Dashboard statistics: total videos, views, followers, likes aggregation |
|
Technology Stack
Core Runtime and Framework
Framework: Express 5.2.1 application server running on Node.js with TypeScript compilation
Key Dependencies
Category | Library | Purpose |
|---|---|---|
Database | mongoose | MongoDB ODM with schema validation |
mongoose-aggregate-paginate-v2 | Pagination for aggregation queries | |
Authentication | jsonwebtoken | JWT token generation/verification |
bcrypt | Password hashing (10 rounds) | |
Security | helmet | HTTP security headers |
express-rate-limit | Request rate limiting (1000/15min) | |
cors | Cross-origin resource sharing | |
File Handling | multer | Multipart form-data parsing |
cloudinary | Media storage and CDN | |
resend | Transactional email service | |
Logging | winston | Structured logging |
winston-daily-rotate-file | Log rotation | |
morgan | HTTP request logging | |
Validation | zod | Schema validation |
Documentation | swagger-jsdoc | OpenAPI spec generation |
swagger-ui-express | Interactive API docs |
System Architecture Layers
High-Level Layer Structure
Middleware Pipeline Configuration
The Express application configures middleware in a specific order to ensure proper request processing:
-
Trust Proxy : Enables proxy support for rate limiting and IP detection
-
CORS : Configures allowed origins, methods, and headers from environment
-
Rate Limiting : Applies 1000 requests per 15 minutes limit to
/apiroutes -
Helmet: Sets security HTTP headers
-
Morgan : Logs HTTP requests in JSON format to Winston logger
-
Static Files : Serves files from
public/directory -
Body Parsers : JSON and URL-encoded data with 16KB limit
-
Cookie Parser : Parses cookies for session management
Core Data Models and Relationships
Entity Relationship Overview

Key Relationships:
-
User-Video: One-to-many relationship where
Video.ownerreferencesUser._id -
Polymorphic Likes:
Likemodel can referenceVideo,Comment, orCommunityPostvia conditional foreign keys -
Polymorphic Comments:
Commentcan belong to eitherVideoorCommunityPost -
Bidirectional Follow:
Follow.followerandFollow.followingboth referenceUser._id -
Many-to-Many Playlists:
Playlist.videosarray contains multipleVideo._idreferences -
Watch History: Embedded array in
User.watchHistorytracking viewed videos
Security Implementation
Security Layers
Layer | Implementation | Configuration |
|---|---|---|
Transport Security | HTTPS-only cookies in production |
|
CORS Protection | Allowed origins, methods, headers | app file configuration |
Rate Limiting | 1000 requests per 15 minutes per IP | app file configuration |
HTTP Headers | Helmet middleware (XSS, clickjacking, etc.) | app file configuration |
Authentication | JWT tokens with HTTP-only cookies |
|
Authorization | Ownership validation in controllers | Resource-specific checks |
Password Security | bcrypt hashing with 10 rounds | Salt generation per password |
Input Validation | Zod schemas for request bodies | Type-safe validation |
File Upload Limits | 100MB video, 5MB thumbnail | Multer configuration |
Session Management | Refresh token rotation, revocation | Stored in User model |
API Documentation
The system provides interactive API documentation through Swagger UI:
-
Endpoint:
/api/v1/docs -
Specification: OpenAPI 3.0 format
-
Generation:
swagger-jsdocfrom inline JSDoc comments -
UI:
swagger-ui-expressfor browser-based testing
All API routes follow RESTful conventions with versioned paths (/api/v1/*). For comprehensive API documentation, see API Documentation.
Database Connection Management
MongoDB Atlas with Mongoose Setup in Node.js
-
Connection String: Use the MongoDB Atlas connection string from environment variables
-
Mongoose Configuration: Connect to MongoDB Atlas using Mongoose
-
Schema Definition: Define schemas using Mongoose models
-
Connection Handling: Manage connection events and errors
-
Indexing: Enable auto-indexing for schemas
External Service Integration
Service Architecture
Cloudinary Integration:
-
Purpose: Cloud-based media storage and CDN delivery
-
Uploads: Videos (MP4), thumbnails, profile images
-
Return Data:
secure_url(CDN URL),public_id(asset identifier) -
Security: Use secure URLs for viewing and
public_idfor deleting items
Resend Integration:
-
Purpose: Transactional email delivery
-
Use Cases: Email verification codes, password reset codes
-
Configuration: API key and sender address from environment variables
-
Sender Address: All outgoing emails use noreply@mail.dancely.in as the sender address.
Logging and Observability
Logging Architecture
Logging Configuration:
-
Transport Layer: Winston with daily log rotation
-
HTTP Logging: Morgan middleware pipes to Winston
-
Log Format: JSON-structured logs with method, URL, status, response time
-
Rotation: Daily log files with automatic archival
-
Log Levels: Error, info, debug for different severity levels
System Health Monitoring
The application provides a health check endpoint for monitoring:
-
Route:
/health -
Handler:
healthCheckRouter -
Purpose: Check if the server is available and working properly
-
Use Case: Used for load balancer health checks and uptime monitoring
Also, use Uptime Robot for monitoring.
Getting Started
Prerequisites
-
Node.js (v18+ recommended)
-
pnpm
-
MongoDB instance
Installation
-
Clone the repository:
git clone https://github.com/sourav6563/dancely-backend.git cd dancely-backend -
Install dependencies:
pnpm install -
Configure environment variables (see Configuration).
-
pnpm run dev -
Build for production:
pnpm run build pnpm start
Configuration
The application requires the following environment variables to be defined in a .env file in the root directory:
Variable | Description |
|---|---|
| |
| Server listening port |
| Connection string for MongoDB |
| Minimum database connection pool size |
| Maximum database connection pool size |
| Secret key for access tokens |
| Expiration time for access tokens |
| Secret key for refresh tokens |
| Expiration time for refresh tokens |
| Allowed origin for CORS |
| Base URL of the API |
| Cloudinary cloud name |
| Cloudinary API key |
| Cloudinary API secret |
| API key for Resend email service |
| Sender email address |
| (Optional) Domain for cookie scoping |