A robust and scalable WebSocket API built with NestJS and Socket.IO for creating and managing real-time chat rooms. Includes a complete web platform for managing rooms, applications, and more.
- Features
- Technologies
- Installation
- Configuration
- Usage
- API Endpoints
- WebSocket Events
- Web Platform
- Project Structure
- Testing
- Contributing
- License
- Real-time room creation and management
- Participant system with customizable names
- Real-time messaging with persistent history
- Multiple simultaneous rooms per user
- Join/leave events with notifications
- Comprehensive metrics system for monitoring
- Application/API Key management for integrations
- Isolated WebSocket namespace (
/ws/rooms) - Robust input validation on all endpoints
- Automatic disconnection handling
- Configurable CORS for different environments
- Detailed logging and error handling
- Modular NestJS architecture for scalability
- Event-driven system with @nestjs/event-emitter
- TypeScript implementation for type safety
- Flexible storage (Redis or in-memory)
- Complete SPA dashboard at
/platform - Room management interface
- Real-time chat interface
- Application/API Key management
- User profile (with Supabase auth)
- GitHub integration for about page
- PWA-ready with manifest files
- Multiple auth methods: Supabase JWT, API Key, Application Key
- Per-application API keys for integrations
- Periodic token validation for Supabase
- Interactive Swagger docs at
/docs/api - HTTP request files for endpoint validation
- Health checks and metrics endpoints
- Comprehensive logging for debugging
- NestJS - Progressive Node.js framework
- Socket.IO - Real-time WebSocket library
- TypeScript - Typed JavaScript
- @nestjs/event-emitter - Event system
- @nestjs/config - Configuration management
- ioredis - Redis client (optional)
- Supabase - Authentication & Database (optional)
- EJS - Template engine
- Tailwind CSS - Utility-first CSS (via CDN)
- Custom CSS - For complex components and animations
- Vanilla JavaScript - For interactivity
- Node.js >= 18.x
- pnpm >= 8.x (recommended) or npm/yarn
- Redis (optional, for persistent storage)
- Supabase project (optional, for authentication)
git clone https://github.com/augustos0204/room-stream-api.git
cd room-stream-apipnpm install
# or
npm installCopy the example file and configure the variables:
cp .env.example .env# π SERVER CONFIGURATION
PORT=3000 # Server port
# π CORS CONFIGURATION
CORS_ORIGIN=* # Allowed origin (* for development)
# π WEBSOCKET CONFIGURATION
WEBSOCKET_NAMESPACE=/ws/rooms # Socket.IO namespace
# π SECURITY CONFIGURATION
API_KEY=your-secret-key # Global API key (optional)
# Generate with: openssl rand -hex 32
# π SUPABASE CONFIGURATION (optional)
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=your-anon-key
# πΎ REDIS CONFIGURATION (optional)
REDIS_URL=redis://localhost:6379
# β±οΈ PRESENCE CONFIGURATION
ROOM_PARTICIPANT_TTL_SECONDS=120 # Participant presence TTL in seconds
# β±οΈ TOKEN VALIDATION
TOKEN_VALIDATION_INTERVAL=300000 # 5 minutes in ms
# π GITHUB CONFIGURATION (optional)
GITHUB_CACHE_ENABLED=true # Enable GitHub API cache
# π± APPLICATION SETTINGS
APP_NAME="RoomStream API"
APP_VERSION=1.0.0pnpm run start:dev # Server in watch mode
pnpm run start:debug # Server with debug enabledpnpm run build # Build for production
pnpm run start:prod # Run compiled versionpnpm run lint # Run ESLint
pnpm run format # Format code with Prettierpnpm run start:devThe server will be available at:
- π― REST API:
http://localhost:3000 - π WebSocket:
ws://localhost:3000/ws/rooms - π Web Platform:
http://localhost:3000/platform - π API Docs:
http://localhost:3000/docs/api
POST /rooms
Content-Type: application/json
{
"name": "My Chat Room"
}GET /roomsGET /rooms/:idDELETE /rooms/:idGET /rooms/:id/messagesGET /rooms/:id/participantsPOST /applications
Authorization: Bearer <supabase-jwt>
Content-Type: application/json
{
"name": "My App",
"description": "Optional description"
}GET /applications
Authorization: Bearer <supabase-jwt>GET /applications/:id
Authorization: Bearer <supabase-jwt>PATCH /applications/:id
Authorization: Bearer <supabase-jwt>
Content-Type: application/json
{
"name": "Updated Name",
"isActive": true
}DELETE /applications/:id
Authorization: Bearer <supabase-jwt>POST /applications/:id/regenerate-key
Authorization: Bearer <supabase-jwt>GET /healthGET /metricsGET /api/github/profileThe API supports multiple authentication methods:
| Method | Use Case | Header/Auth |
|---|---|---|
| Application Key | Server-to-server | auth.applicationKey |
| Supabase JWT | User authentication | Authorization: Bearer |
| Global API Key | Simple API access | x-api-key header |
Create an application via the API or Platform to get an API key:
// WebSocket connection with application key
const socket = io('http://localhost:3000/ws/rooms', {
auth: { applicationKey: 'app_your64hexcharacters...' }
});// WebSocket connection with Supabase token
const socket = io('http://localhost:3000/ws/rooms', {
auth: { token: 'supabase-jwt-token' }
});# REST API
curl -H "x-api-key: your-api-key" http://localhost:3000/rooms
# WebSocket
const socket = io('http://localhost:3000/ws/rooms', {
auth: { apiKey: 'your-api-key' }
});Note: If no authentication is configured, the API is open (useful for development).
const socket = io('http://localhost:3000/ws/rooms');
// With authentication
const socket = io('http://localhost:3000/ws/rooms', {
auth: {
token: 'supabase-jwt', // OR
applicationKey: 'app_...', // OR
apiKey: 'global-api-key'
}
});socket.emit('joinRoom', {
roomId: 'room-id',
participantName: 'Your Name' // optional
});socket.emit('leaveRoom', {
roomId: 'room-id'
});socket.emit('sendMessage', {
roomId: 'room-id',
message: 'Your message here'
});
// Or use 'emit' for custom events
socket.emit('emit', {
roomId: 'room-id',
message: 'Custom event data',
event: 'custom-event-name' // optional, defaults to 'message'
});socket.emit('getRoomInfo', {
roomId: 'room-id'
});socket.emit('updateParticipantName', {
roomId: 'room-id',
participantName: 'New Name'
});socket.on('joinedRoom', (data) => {
console.log('Joined room:', data);
// { roomId, roomName, participants, recentMessages }
});socket.on('userJoined', (data) => {
console.log('User joined:', data);
// { clientId, participantName, roomId, roomName, participantCount }
});socket.on('userLeft', (data) => {
console.log('User left:', data);
// { clientId, participantName, roomId, roomName, participantCount }
});socket.on('newMessage', (data) => {
console.log('New message:', data);
// { id, clientId, message, timestamp, roomId, event }
});socket.on('roomInfo', (data) => {
console.log('Room info:', data);
// { id, name, participantCount, participants, messageCount, createdAt }
});socket.on('participantNameUpdated', (data) => {
console.log('Name updated:', data);
// { clientId, participantName, roomId }
});socket.on('roomDeleted', (data) => {
console.log('Room deleted:', data);
// { roomId, roomName, message }
});socket.on('error', (error) => {
console.error('Error:', error);
// { message: 'Error description' }
});The web platform at /platform provides a complete interface for:
| Route | Description |
|---|---|
/platform |
Dashboard with overview |
/platform/rooms |
Room listing and management |
/platform/chat |
Real-time chat interface |
/platform/applications |
API Key management |
/platform/profile |
User profile (requires auth) |
/platform/login |
Authentication page |
/platform/about |
About page with GitHub integration |
/platform/guide |
Documentation and usage guide |
/platform/landing |
Landing page |
- SPA Architecture: Smooth navigation without page reloads
- Responsive Design: Works on desktop and mobile
- Real-time Updates: Live room and message updates
- Dark Mode Ready: CSS custom properties for theming
- PWA Support: Manifest files for installation
src/
βββ π application/ # Application/API Key management
β βββ application.controller.ts
β βββ application.module.ts
β βββ application.service.ts
β βββ dto/
βββ π common/ # Shared utilities
β βββ config/ # Configuration helpers
β βββ decorators/ # Custom decorators (@Public)
β βββ dto/ # Shared DTOs
β βββ filters/ # Exception filters
β βββ guards/ # Auth guards
β βββ interceptors/ # Request interceptors
β βββ interfaces/ # Shared interfaces
β βββ utils/ # Utility functions
βββ π events/ # Event system
β βββ events.module.ts
β βββ events.service.ts
β βββ metrics.events.ts
βββ π github/ # GitHub integration
β βββ github.controller.ts
β βββ github.module.ts
β βββ github.service.ts
βββ π health/ # Health checks
β βββ health.controller.ts
β βββ health.module.ts
β βββ health.service.ts
βββ π memory/ # Storage abstraction
β βββ adapters/ # In-memory & Redis adapters
β βββ interfaces/
β βββ memory.module.ts
β βββ memory.service.ts
βββ π metrics/ # System metrics
β βββ metrics.controller.ts
β βββ metrics.module.ts
β βββ metrics.service.ts
βββ π platform/ # Web platform
β βββ pages/ # SPA pages (EJS)
β βββ components/ # Reusable components
β βββ public/ # Static assets & error pages
β β βββ styles/ # CSS files
β β βββ scripts/ # JavaScript files
β β βββ media/ # Images, icons
β βββ platform.controller.ts
β βββ platform.module.ts
β βββ pages.service.ts
βββ π room/ # Core - Chat rooms
β βββ dto/ # Room DTOs
β βββ interfaces/ # Room interfaces
β βββ room.controller.ts # REST endpoints
β βββ room.gateway.ts # WebSocket gateway
β βββ room.module.ts
β βββ room.service.ts # Business logic
βββ π supabase/ # Supabase integration
β βββ supabase.module.ts
β βββ supabase.service.ts
βββ π types/ # Shared types
βββ app.controller.ts
βββ app.module.ts
βββ app.service.ts
βββ main.ts # Entry point
# Unit tests
pnpm run test
# Tests in watch mode
pnpm run test:watch
# E2E tests
pnpm run test:e2e
# Coverage
pnpm run test:covUse the Swagger UI at /docs/api or the provided .http files in the requests/ folder.
The system automatically collects metrics:
- Connections: Connected/disconnected users
- Rooms: Created/deleted
- Messages: Sent per room
- Participants: Room join/leave events
Detailed logs for all operations:
[RoomGateway] Client connected on namespace /ws/rooms: abc123
[RoomService] Room created: room_1234567890_abc (My Room)
[RoomGateway] Client abc123 joined room: room_1234567890_abc- Fork the project
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add: AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
feat:New featurefix:Bug fixdocs:Documentationstyle:Formattingrefactor:Refactoringtest:Testschore:Maintenance
NODE_ENV=production
PORT=3000
CORS_ORIGIN=https://your-domain.com
WEBSOCKET_NAMESPACE=/ws/rooms
API_KEY=your-secure-api-key-here
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=your-anon-key
REDIS_URL=redis://your-redis-host:6379# Build
docker build -t roomstream-api .
# Run
docker run -p 3000:3000 --env-file .env roomstream-api- Documentation: Check this README and
/docs/api - Issues: Use GitHub Issues
- Contact: Start a discussion in the repository