{"id":48037678,"url":"https://github.com/krotrn/chatapp-backend","last_synced_at":"2026-04-04T14:00:20.742Z","repository":{"id":278821982,"uuid":"936201954","full_name":"krotrn/ChatApp-backend","owner":"krotrn","description":"Real-time Chat Backend built with Node.js, Express, TypeScript, MongoDB, and Socket.IO. Supports direct and group messaging, message editing, reactions, file attachments, read receipts, and more — all with real-time updates and JWT-based authentication.","archived":false,"fork":false,"pushed_at":"2025-09-13T16:15:29.000Z","size":891,"stargazers_count":6,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-09-13T18:25:28.041Z","etag":null,"topics":["express-js","mongodb","nodejs","socket-io","typescript"],"latest_commit_sha":null,"homepage":"https://chat-backend-kr.vercel.app","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/krotrn.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-02-20T17:33:59.000Z","updated_at":"2025-09-13T16:15:26.000Z","dependencies_parsed_at":null,"dependency_job_id":"092be632-df0d-4aa1-804e-a4c128c605be","html_url":"https://github.com/krotrn/ChatApp-backend","commit_stats":null,"previous_names":["krotrn/chatapp-backend"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/krotrn/ChatApp-backend","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krotrn%2FChatApp-backend","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krotrn%2FChatApp-backend/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krotrn%2FChatApp-backend/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krotrn%2FChatApp-backend/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/krotrn","download_url":"https://codeload.github.com/krotrn/ChatApp-backend/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krotrn%2FChatApp-backend/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31402277,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-04T10:20:44.708Z","status":"ssl_error","status_checked_at":"2026-04-04T10:20:06.846Z","response_time":60,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["express-js","mongodb","nodejs","socket-io","typescript"],"created_at":"2026-04-04T14:00:16.497Z","updated_at":"2026-04-04T14:00:20.419Z","avatar_url":"https://github.com/krotrn.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Chat Backend\n\nA production-ready real-time chat backend service built with Node.js, Express, and TypeScript. This service powers comprehensive chat functionality including direct messaging, group chats, file sharing, and real-time communication features. It uses MongoDB for chat data storage and integrates with external user validation services.\n\nThe backend provides RESTful APIs for chat management and WebSocket connections for real-time messaging, typing indicators, user presence, and live notifications.\n\n## Features\n\n- **Real-time Communication**: WebSocket integration using Socket.IO for instant messaging\n- **Comprehensive Chat Management**:\n  - Create and manage one-on-one conversations\n  - Group chat creation, member management (add/remove participants)\n  - Chat archival and deletion functionality\n- **Advanced Message Operations**:\n  - Send, edit, delete, and reply to messages\n  - Pin/unpin important messages in chats\n  - React to messages with emojis\n  - Message read receipts and status tracking\n- **File Attachment Support**: Upload and share files with URL-based storage\n- **Real-time Features**:\n  - Live typing indicators\n  - User online/offline presence tracking\n  - Instant message delivery and notifications\n- **Authentication \u0026 Security**:\n  - JWT-based authentication system\n  - Rate limiting protection (5000 requests per 15 minutes)\n  - CORS configuration for secure cross-origin requests\n- **Performance \u0026 Monitoring**:\n  - Message pagination for efficient data loading\n  - Request logging with Morgan\n  - Response compression for improved performance\n  - Connection health monitoring\n- **Developer Experience**:\n  - Full TypeScript support with strict typing\n  - Comprehensive API documentation\n  - ESLint and Prettier for code quality\n  - Hot-reloading development environment\n\n## Tech Stack\n\n- **Runtime**: Node.js with Express.js framework\n- **Language**: TypeScript for type-safe development\n- **Database**: MongoDB with Mongoose ODM for chat data storage\n- **Real-time Communication**: Socket.IO for WebSocket connections\n- **Authentication**: JWT (JSON Web Tokens) for secure authentication\n- **File Upload**: Multer for handling multipart/form-data\n- **External Integrations**:\n  - PostgreSQL client (`pg`) for user validation\n  - Axios for HTTP requests to external services\n- **Development Tools**:\n  - ESLint with TypeScript support for code linting\n  - Prettier for code formatting\n  - ts-node-dev for development hot-reloading\n- **Middleware \u0026 Utilities**:\n  - CORS for cross-origin resource sharing\n  - Morgan for HTTP request logging\n  - Express Rate Limit for API protection\n  - Compression for response optimization\n  - Cookie Parser for cookie handling\n  - Request IP for client IP detection\n\n## Prerequisites\n\n- **Node.js**: Version 18.x or higher (based on TypeScript definitions)\n- **MongoDB**: Local installation or MongoDB Atlas cloud instance\n- **Package Manager**: npm (comes with Node.js) or yarn\n- **Environment**: Access to external user validation service (PostgreSQL-based)\n- **Docker** (Optional): For containerized development and deployment\n\n## Installation and Setup\n\n### Option 1: Docker Setup (Recommended)\n\n1.  **Clone the repository**:\n\n    ```bash\n    git clone https://github.com/krotrn/chat-backend.git\n    cd chat-backend\n    ```\n\n2.  **Environment Configuration**:\n    Copy the example environment file and configure your settings:\n\n    ```bash\n    cp .env.example .env\n    ```\n\n    Edit the `.env` file with your configuration:\n\n    ```bash\n    # MongoDB Configuration (Docker will handle this)\n    MONGODB_URI=mongodb://mongodb:27017/chat-app\n\n    # Application Configuration\n    JWT_SECRET=your_super_secret_jwt_key\n    NODE_ENV=development\n    PORT=8000\n\n    # External Service Configuration\n    CLIENT_URL=http://localhost:3000\n    DATABASE_URL=your_external_postgres_connection_string\n    SESSION_SECRET=your_sessions_secret_key\n    ```\n\n3.  **Start with Docker**:\n\n    ```bash\n    # Start development environment with all services\n    npm run docker:dev\n\n    # Or start in detached mode (background)\n    npm run docker:dev:detached\n\n    # View logs\n    npm run docker:logs\n\n    # Stop services\n    npm run docker:stop\n    ```\n\n    This will start:\n\n    - Chat Backend on `http://localhost:8000`\n    - MongoDB on `localhost:27017`\n\n4.  **Verify the setup**:\n    - Visit `http://localhost:8000/api/v1/health` to check if the server is running\n    - All databases are automatically configured and connected\n\n### Option 2: Local Development Setup\n\n1.  **Clone the repository**:\n\n    ```bash\n    git clone https://github.com/krotrn/chat-backend.git\n    cd chat-backend\n    ```\n\n2.  **Install dependencies**:\n\n    ```bash\n    npm install\n    ```\n\n3.  **Environment Configuration**:\n    Copy the example environment file and configure your settings:\n\n    ```bash\n    cp .env.example .env\n    ```\n\n    Edit the `.env` file with your configuration:\n\n    ```bash\n    # MongoDB Configuration\n    MONGODB_URI=mongodb://localhost:27017/chat-app\n\n    # Application Configuration\n    JWT_SECRET=your_super_secret_jwt_key\n    NODE_ENV=development\n    PORT=8000\n\n    # External Service Configuration\n    CLIENT_URL=http://localhost:3000\n    DATABASE_URL=postgres://user:password@localhost:5432/your_database\n    SESSION_SECRET=your_sessions_secret_key\n    ```\n\n4.  **Start the development server**:\n\n    ```bash\n    npm run dev\n    ```\n\n    The server will start on `http://localhost:8000` (or your configured PORT) with hot-reloading enabled.\n\n5.  **Verify the setup**:\n    - Visit `http://localhost:8000/api/v1/health` to check if the server is running\n    - Check the console for successful MongoDB connection\n    - Ensure WebSocket connection is available at `ws://localhost:8000`\n\n## Scripts\n\n### Development Scripts\n\n- `npm run dev`: Start development server with hot-reloading using `ts-node-dev`.\n- `npm run build`: Compile TypeScript to JavaScript.\n- `npm run stage`: Compile TypeScript and stage all changes for commit (`tsc \u0026\u0026 git add .`).\n\n### Code Quality Scripts\n\n- `npm run lint`: Lint TypeScript files using ESLint.\n- `npm run lint:fix`: Automatically fix ESLint issues.\n- `npm run format`: Format code with Prettier.\n- `npm run format:check`: Check formatting with Prettier without making changes.\n- `npm run validate`: Run both linting and format checking.\n\n### Docker Scripts\n\n- `npm run docker:dev`: Start development environment with Docker Compose.\n- `npm run docker:dev:detached`: Start development environment in background.\n- `npm run docker:prod`: Start production environment with Docker Compose.\n- `npm run docker:stop`: Stop all Docker services.\n- `npm run docker:clean`: Stop services and remove volumes (⚠️ Data loss!).\n- `npm run docker:logs`: View backend service logs.\n- `npm run docker:shell`: Open shell in backend container.\n\n### Docker Helper Script (Linux/macOS)\n\nFor more advanced Docker operations, use the included helper script:\n\n```bash\n# Make script executable\nchmod +x docker.sh\n\n# Available commands\n./docker.sh help                 # Show all available commands\n./docker.sh dev:start            # Start development environment\n./docker.sh dev:logs             # View logs\n./docker.sh db:backup            # Create database backup\n./docker.sh health               # Check service health\n```\n\n## API Endpoints\n\nThe chat backend provides a comprehensive RESTful API organized around REST principles. All requests and responses use JSON format and follow standardized response structures.\n\n### Base URL\n\n```\nhttp://localhost:8000/api/v1\n```\n\n### Authentication\n\nMost API requests require authentication via a JWT token in the `Authorization` header:\n\n```\nAuthorization: Bearer \u003cyour_jwt_token\u003e\n```\n\n### API Categories\n\n- **Chat Management** (`/chats/*`): 14 endpoints for creating, managing, and deleting conversations\n- **Message Operations** (`/messages/*`): 7 endpoints for sending, editing, and managing messages\n- **Webhook Integration** (`/webhooks/*`): 3 endpoints for external service integration\n- **Health Check** (`/health`): Server status monitoring\n\n### Quick Reference\n\n**Popular Endpoints:**\n\n- `POST /chats` - Create a new chat (one-on-one or group)\n- `GET /chats` - Get all user's chats with pagination\n- `POST /messages` - Send a message to a chat\n- `GET /messages/:chatId` - Get messages from a specific chat\n- `POST /chats/:chatId/pin/:messageId` - Pin a message in a chat\n- `GET /health` - Check server health status\n\n📖 **For complete API documentation with request/response examples, authentication details, and WebSocket events, see [API_DOC.md](./API_DOC.md)**\n\n## WebSocket Events\n\nThe application uses Socket.IO for real-time communication. The backend supports **25+ WebSocket events** across different categories:\n\n### Event Categories\n\n- **🔗 Connection \u0026 Presence** (8 events): User online/offline status, connection management\n- **💬 Chat Room Management** (4 events): Joining/leaving chats, participant updates\n- **📨 Messaging \u0026 Interactions** (9 events): Real-time messaging, typing indicators, reactions\n- **⚙️ Chat Metadata** (5 events): Chat creation, updates, deletions\n\n### Key Real-time Features\n\n- **Live Messaging**: Instant message delivery with `messageReceived` event\n- **Typing Indicators**: Real-time typing status with `typing`/`stopTyping` events\n- **User Presence**: Online/offline status tracking with `userOnline`/`userOffline` events\n- **Message Interactions**: Live reactions, pins, edits, and deletions\n- **Group Management**: Real-time participant additions/removals\n\n### Example Events\n\n```javascript\n// Client connects and joins a chat\nsocket.emit(\"joinChat\", { chatId: \"chat123\" });\n\n// Send typing indicator\nsocket.emit(\"typing\", { chatId: \"chat123\", userId: \"user456\" });\n\n// Receive new message\nsocket.on(\"messageReceived\", (messageData) =\u003e {\n  // Handle incoming message\n});\n\n// Track user presence\nsocket.on(\"userIsOnline\", ({ userId }) =\u003e {\n  // Update user status to online\n});\n```\n\n📖 **For the complete list of WebSocket events with payload structures and usage examples, see [API_DOC.md](./API_DOC.md#websocket-events)**\n\n## Docker Configuration\n\nThe project includes a comprehensive Docker setup for both development and production environments.\n\n### Services Included\n\n- **Chat Backend**: Main application server\n- **MongoDB**: Primary database for chat data\n\n### Development Environment\n\n```bash\n# Start all services for development\nnpm run docker:dev\n\n# Start in background\nnpm run docker:dev:detached\n\n# View logs\nnpm run docker:logs\n\n# Open shell in backend container\nnpm run docker:shell\n```\n\n**Development Features:**\n\n- Hot reloading with volume mounts\n- Debug mode enabled for Socket.IO\n- All source code changes reflect immediately\n- Exposed ports: Backend (8000), MongoDB (27017)\n\n### Production Environment\n\n```bash\n# Build and start production services\nnpm run docker:prod\n\n# View production logs\ndocker-compose logs -f chat-backend-prod\n```\n\n**Production Features:**\n\n- Multi-stage build for optimized images\n- Non-root user for security\n- Health checks included\n- Minimal attack surface\n- Production-optimized Node.js runtime\n\n### Docker Commands Reference\n\n| Command                | Description                    |\n| ---------------------- | ------------------------------ |\n| `npm run docker:dev`   | Start development environment  |\n| `npm run docker:prod`  | Start production environment   |\n| `npm run docker:stop`  | Stop all services              |\n| `npm run docker:clean` | Remove all volumes and cleanup |\n| `npm run docker:logs`  | View backend logs              |\n| `npm run docker:shell` | Access backend container shell |\n\n### Environment Variables for Docker\n\nWhen using Docker, update your `.env` file with these Docker-optimized settings:\n\n```bash\n# Database connections use Docker service names\nMONGODB_URI=mongodb://mongodb:27017/chat-app\n\n# External database connection (not containerized)\nDATABASE_URL=your_external_postgres_connection_string\n\n# Keep other settings as needed\nJWT_SECRET=your_super_secret_jwt_key\nNODE_ENV=development\nPORT=8000\nCLIENT_URL=http://localhost:3000\nSESSION_SECRET=your_sessions_secret_key\n```\n\n## Project Structure\n\n```\nchat-backend/\n├── src/\n│   ├── controllers/     # Request handlers and business logic\n│   │   ├── chat/        # Chat management controllers (general, group, one-on-one, pin)\n│   │   └── message/     # Message operation controllers\n│   ├── database/        # Database connection setup (MongoDB)\n│   ├── middleware/      # Express middleware (auth, error handling, validation)\n│   ├── models/          # Mongoose schemas and models for MongoDB\n│   ├── routes/          # API route definitions (chat, message, webhooks)\n│   ├── socket/          # Socket.IO event handlers and real-time logic\n│   ├── types/           # TypeScript type definitions and interfaces\n│   ├── utils/           # Utility functions, constants, and helper modules\n│   └── index.ts         # Application entry point and server configuration\n├── public/              # Static assets directory\n├── .env.example         # Environment variables template\n├── .gitignore           # Git ignore configuration\n├── eslint.config.mjs    # ESLint configuration\n├── LICENSE              # MIT License file\n├── package.json         # Dependencies, scripts, and project metadata\n├── tsconfig.json        # TypeScript compiler configuration\n├── API_DOC.md           # Comprehensive API documentation\n└── README.md            # Project documentation (this file)\n```\n\n### Key Directories\n\n- **`src/controllers/`**: Contains organized business logic split by feature (chat management, message operations)\n- **`src/routes/`**: Express route definitions with proper middleware integration\n- **`src/socket/`**: Real-time WebSocket event handling for instant communication\n- **`src/models/`**: MongoDB schemas using Mongoose for data modeling\n- **`src/types/`**: TypeScript interfaces ensuring type safety across the application\n- **`src/utils/`**: Shared utilities, constants, and helper functions\n\n## Response Types\n\nThe API aims to use standardized response structures.\n\n### Success Response Example\n\n```json\n{\n  \"statusCode\": 200,\n  \"data\": {\n    /* Response data */\n  },\n  \"message\": \"Operation successful\",\n  \"success\": true\n}\n```\n\n### Error Response Example\n\n```json\n{\n  \"statusCode\": 404,\n  \"data\": null,\n  \"message\": \"Resource not found\",\n  \"success\": false,\n  \"errors\": [\n    /* Optional: array of specific error details */\n  ]\n}\n```\n\n## Contributing\n\nWe welcome contributions to improve the chat backend! Please follow these steps:\n\n1. **Fork the repository** on GitHub\n2. **Create a feature branch**: `git checkout -b feature/amazing-feature`\n3. **Follow the coding standards**:\n   - Run `npm run validate` to check linting and formatting\n   - Ensure TypeScript compilation passes: `npm run build`\n   - Write meaningful commit messages\n4. **Commit your changes**: `git commit -m 'Add some amazing feature'`\n5. **Push to your branch**: `git push origin feature/amazing-feature`\n6. **Open a Pull Request** with a clear description of the changes\n\n### Development Guidelines\n\n- Maintain TypeScript strict mode compliance\n- Follow existing code organization patterns\n- Add appropriate error handling and logging\n- Update API documentation for new endpoints\n- Test WebSocket events thoroughly\n\n## License\n\nThis project is licensed under the **MIT License** - see the [LICENSE](./LICENSE) file for details.\n\n## Contact \u0026 Support\n\n- **Issues**: [GitHub Issues](https://github.com/krotrn/chat-backend/issues)\n- **Documentation**: See [API_DOC.md](./API_DOC.md) for detailed API reference\n- **Questions**: Open a discussion or issue on the GitHub repository\n\n---\n\n**Built with ❤️ using Node.js, TypeScript, and Socket.IO**\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkrotrn%2Fchatapp-backend","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkrotrn%2Fchatapp-backend","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkrotrn%2Fchatapp-backend/lists"}