A Express.js and Socket.io based event server that delivers MySQL database changes to clients in real-time. Provides secure and scalable real-time data transmission with JWT authentication and hierarchical channel structure.
- π JWT Authentication: Token-based secure connection and authorization
- π‘ Real-Time Event Publishing: Database changes (insert, update, delete) are transmitted instantly
- ποΈ Hierarchical Channel Structure: Flexible listening based on tables, operations, and record IDs
- π Room Logic: Clients only receive events from channels they subscribe to
- π¨ Modern Web UI: Responsive design with Bootstrap 5 and JSON syntax highlighting
- π‘οΈ CORS Support: Secure and customizable cross-origin connections
- π Table-Based Authorization: Users can only listen to tables they have permission for
- Node.js (v16+ recommended)
- npm or yarn
git clone <repository-url> cd universaldb-socketnpm installcp .env.example .env # Edit the .env file with your configuration# Development mode (auto-restart) npm run dev # Production mode npm startVisit link in your browser: http://localhost:3001/
Visit link in your browser: http://localhost:3001/monitor.html
universaldb-socket/ βββ src/ β βββ app.js # Main application class β βββ config/ β β βββ server.js # Server configuration β β βββ jwt.js # JWT configuration β βββ controllers/ β β βββ socketController.js # Socket.io controller β β βββ apiController.js # REST API controller β βββ middleware/ β β βββ auth.js # Authentication middleware β β βββ rateLimiter.js # Rate limiting middleware β β βββ errorHandler.js # Error handling middleware β βββ services/ β β βββ eventService.js # Event publishing service β β βββ socketService.js # Socket management service β βββ utils/ β β βββ logger.js # Logging utility β β βββ validator.js # Data validation utility β βββ routes/ β βββ api.js # API routes βββ public/ β βββ index.html # Main web interface β βββ monitor.html # Monitoring web interface β βββ css/ β β βββ style.css # CSS styles β βββ js/ β βββ client.js # Client JavaScript library βββ server.js # Main entry point βββ package.json # Project dependencies βββ .env.example # Environment variables example βββ .gitignore # Git ignore file βββ README.md # This file { "dependencies": { "express": "^5.1.0", "jsonwebtoken": "^9.0.2", "socket.io": "^4.8.1" } }Set the JWT_SECRET value as an environment variable in production:
export JWT_SECRET="your-super-secret-key"| Channel Format | Description | Example |
|---|---|---|
db | All database changes | All events |
db.[table] | Specific table | db.users |
db.[table].[action] | Table + operation type | db.users.insert |
db.[table].[action].[id] | Table + operation + record ID | db.users.update.123 |
db.[table].*.[id] | Table + record ID (all operations) | db.users.*.123 |
db.*.[action] | All tables + specific operation | db.*.delete |
// Listen to insert operations in all tables socket.emit('subscribe', 'db.*.insert'); // Listen to all operations in users table socket.emit('subscribe', 'db.users'); // Listen to all changes of a specific record socket.emit('subscribe', 'db.products.*.456');{ "timestamp": "2024-01-15T10:30:45.123Z", "table": "users", "action": "update", "record": { "id": 123, "name": "John Doe", "email": "john@example.com", "updated_at": "2024-01-15T10:30:45.123Z" } }insert- Adding new recordupdate- Updating existing recorddelete- Deleting record
JWT token structure used for Socket.io connections:
{ "sub": "user_id", "name": "User Name", "tables": "users,products,orders", "iat": 1753215601, "exp": 1753219201 }Token Fields:
sub: User ID (string)name: User name (string)tables: Accessible tables (comma-separated string)iat: Token creation time (Unix timestamp)exp: Token expiration time (Unix timestamp)
Admin or Publisher JWT token structure used for DB change requests from external systems (CodeIgniter, Laravel, Node.js etc.):
{ "sub": "admin_id", "name": "Admin Name", "admin": true, "publisher": false, "iat": 1753215601, "exp": 1753219201 }Token Fields:
sub: Unique identifier of admin system (string)name: Display name of admin system (string)admin: Admin privilege (boolen)publisher: Publisher privilege (boolen)iat: Token creation time (Unix timestamp)exp: Token expiration time (Unix timestamp)
Authorization System:
- User JWT: Access only to tables specified in
tablesfield - Admin JWT: Full access to all tables, bypasses rate limiter
- Publisher JWT: Access to publish events with rate limiter, but not to subscribe to channels
- Empty
tablesfield grants no table access
const io = require('socket.io-client'); const jwt = require('jsonwebtoken'); // Create JWT token const token = jwt.sign({ sub: 'user123', name: 'John Doe', tables: ['users', 'posts'] }, 'your-secret-key'); // Socket connection const socket = io('http://localhost:3001', { auth: { token: token } });Event sending endpoint
Request Body:
{ "timestamp":"2024-01-15T10:30:00.000Z", "action":"update", "table":"pages", "record":{ "id":12, "title":"Test" } }Headers:
Authorization: Bearer <JWT_TOKEN> Content-Type: application/json Response:
{ "success": true, "message": "Event published successfully", "eventsPublished": 6, "timestamp": "2025-07-23T09:03:45.261Z" } ## π» Client Usage ### JavaScript (Browser/Node.js) ```javascript const socket = io('http://localhost:3001', { auth: { token: 'your-jwt-token' } }); // Subscribe to channel socket.emit('subscribe', 'db.users.insert'); // Listen to events socket.on('dbChange', (data) => { console.log('Database change:', data); }); // Check connection status socket.on('connect', () => { console.log('Connected to server'); }); socket.on('disconnect', () => { console.log('Disconnected from server'); }); import socketio import jwt import json # Create JWT token token = jwt.encode({ 'sub': 'user123', 'name': 'Python Client', 'tables': ['users', 'orders'] }, 'your-secret-key', algorithm='HS256') # Socket.io client sio = socketio.Client() @sio.event def connect(): print('Connected to server') # Subscribe to channel sio.emit('subscribe', 'db.users') @sio.event def dbChange(data): print('Database change received:', json.dumps(data, indent=2)) @sio.event def disconnect(): print('Disconnected from server') # Connect sio.connect('http://localhost:3001', auth={'token': token}) sio.wait()// Subscribe to channel socket.emit('subscribe', 'db.users.update', (joinedChannels) => { console.log('Subscribed channels:', joinedChannels); }); // Listen to events socket.on('db.users.update', (data) => { console.log('User updated:', data); });const changeData = { table: 'users', action: 'update', data: { id: 123, name: 'John Updated', email: 'john.updated@example.com' }, timestamp: new Date().toISOString() }; // Send via Socket socket.emit('dbChange', changeData); // Send via HTTP API fetch('http://localhost:3001/api/events', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${jwtToken}` }, body: JSON.stringify(changeData) });# .env file PORT=3001 JWT_SECRET=your-super-secret-jwt-key CORS_ORIGIN=* LOG_LEVEL=info RATE_LIMIT_WINDOW=60000 RATE_LIMIT_MAX=100// src/config/server.js module.exports = { port: process.env.PORT || 3001, cors: { origin: process.env.CORS_ORIGIN || "*", methods: ["GET", "POST"] }, rateLimit: { windowMs: parseInt(process.env.RATE_LIMIT_WINDOW) || 60000, max: parseInt(process.env.RATE_LIMIT_MAX) || 100 } };- Emit Panel: Event sending form
- Listening Panel: Channel subscription and live event display
- JSON Syntax Highlighting: Colorful and readable JSON format
- Responsive Design: Mobile-friendly with Bootstrap 5
- Real-time Updates: Instant event streaming
pages- Page managementcategories- Category systemusers- User managementproducts- Product catalogorders- Order trackingcomments- Comment system
subscribe(channel, callback)- Subscribe to channeldbChange(data)- Report database change
db.*- Hierarchical event channelserror- Error messages
GET /- Server status check
PORT=3001 JWT_SECRET=your-production-secret-key NODE_ENV=productionnpm install -g pm2 pm2 start server.js --name universaldb-socket-serverFROM node:16-alpine WORKDIR /app COPY package*.json ./ RUN npm install --production COPY . . EXPOSE 3001 CMD ["node", "server.js"]- Redis Adapter: For horizontal scaling
- Load Balancer: Multiple instance support
- Connection Pooling: Database connection optimization
- Rate Limiting: DDoS protection
// Connection count tracking io.engine.clientsCount // Room information io.sockets.adapter.roomsDEBUG=socket.io:* node server.js# Unit tests npm test # Coverage report npm run coverage # Linting npm run lint- Fork the project
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
MIT License - See the LICENSE file for details.
- Quick Start Guide - Get the project running in 5 minutes
- Developer Guide - Comprehensive developer documentation
- API Examples - Detailed usage examples and best practices
http://localhost:3001/index.html- Test interface and example usage (public/index.html)http://localhost:3001/monitor.html- Monitor interface and example usage (public/monitor.html).env.example- Environment variables templatesrc/- Main source code
- Issues: Use GitHub Issues page
- Developer Guide: DEVELOPER_GUIDE.md
- API Examples: API_EXAMPLES.md
- Quick Start: QUICK_START.md
Developer: Εafak BahΓ§e Version: 1.0.0