Configuring WebSocket Communication in Node.js
Learn how to set up and manage WebSocket connections in Node.js for real-time communication between clients and servers.
0 likes
3 views
Rule Content
{ "title": "Configuring WebSocket Communication in Node.js", "description": "Guidelines for setting up and managing WebSocket connections in Node.js to facilitate real-time communication between clients and servers.", "category": "Node.js Cursor Rules", "rules": [ { "name": "Use Secure WebSocket Connections", "description": "Always implement WebSocket Secure (wss://) to encrypt data transmission between the client and server, ensuring data integrity and confidentiality.", "code": [ "const https = require('https');", "const fs = require('fs');", "const WebSocket = require('ws');", "", "const server = https.createServer({", " cert: fs.readFileSync('path/to/cert.pem'),", " key: fs.readFileSync('path/to/key.pem')", "});", "", "const wss = new WebSocket.Server({ server });", "", "server.listen(8080, () => {", " console.log('Secure WebSocket server is listening on port 8080');", "});" ] }, { "name": "Implement Connection Lifecycle Management", "description": "Handle WebSocket connection events ('open', 'message', 'close', 'error') to manage the connection lifecycle effectively and ensure application stability.", "code": [ "wss.on('connection', (ws) => {", " console.log('Client connected');", "", " ws.on('message', (message) => {", " console.log(`Received message: ${message}`);", " // Process the message", " });", "", " ws.on('close', () => {", " console.log('Client disconnected');", " });", "", " ws.on('error', (error) => {", " console.error(`WebSocket error: ${error}`);", " });", "});" ] }, { "name": "Validate Incoming Messages", "description": "Ensure all incoming messages are validated to prevent processing of malformed or harmful data, enhancing application security.", "code": [ "ws.on('message', (message) => {", " try {", " const data = JSON.parse(message);", " // Validate data structure and content", " // Process the validated data", " } catch (error) {", " console.error('Invalid message received:', error);", " ws.send('Error: Invalid message format');", " }", "});" ] }, { "name": "Implement Heartbeat Mechanism", "description": "Use a heartbeat mechanism to detect and close inactive or unresponsive WebSocket connections, maintaining server performance.", "code": [ "const interval = setInterval(() => {", " wss.clients.forEach((ws) => {", " if (ws.isAlive === false) return ws.terminate();", " ws.isAlive = false;", " ws.ping();", " });", "}, 30000); // Send a ping every 30 seconds", "", "wss.on('connection', (ws) => {", " ws.isAlive = true;", " ws.on('pong', () => {", " ws.isAlive = true;", " });", "});" ] }, { "name": "Implement Authentication and Authorization", "description": "Ensure only authenticated and authorized users can establish WebSocket connections to protect sensitive data and resources.", "code": [ "const jwt = require('jsonwebtoken');", "", "wss.on('connection', (ws, req) => {", " const token = req.headers['sec-websocket-protocol'];", " if (!token) {", " ws.close(1008, 'Authentication required');", " return;", " }", "", " jwt.verify(token, 'your_secret_key', (err, decoded) => {", " if (err) {", " ws.close(1008, 'Invalid token');", " return;", " }", " // Proceed with the connection", " });", "});" ] }, { "name": "Limit Number of Connections", "description": "Set a maximum number of concurrent WebSocket connections to prevent server overload and potential denial-of-service attacks.", "code": [ "const MAX_CONNECTIONS = 100;", "let connectionCount = 0;", "", "wss.on('connection', (ws) => {", " if (connectionCount >= MAX_CONNECTIONS) {", " ws.close(1000, 'Connection limit reached');", " return;", " }", " connectionCount++;", "", " ws.on('close', () => {", " connectionCount--;", " });", "});" ] }, { "name": "Implement Rate Limiting", "description": "Apply rate limiting to control the number of messages a client can send within a specific timeframe, mitigating potential abuse.", "code": [ "const rateLimit = require('express-rate-limit');", "", "const limiter = rateLimit({", " windowMs: 15 * 60 * 1000, // 15 minutes", " max: 100 // Limit each IP to 100 requests per windowMs", "});", "", "app.use(limiter);" ] }, { "name": "Log WebSocket Events", "description": "Implement logging for WebSocket events and errors to facilitate monitoring, debugging, and maintenance of the application.", "code": [ "const winston = require('winston');", "", "const logger = winston.createLogger({", " transports: [", " new winston.transports.Console(),", " new winston.transports.File({ filename: 'combined.log' })", " ]", "});", "", "wss.on('connection', (ws) => {", " logger.info('Client connected');", "", " ws.on('message', (message) => {", " logger.info(`Received message: ${message}`);", " });", "", " ws.on('close', () => {", " logger.info('Client disconnected');", " });", "", " ws.on('error', (error) => {", " logger.error(`WebSocket error: ${error}`);", " });", "});" ] } ] }