Building Real-Time Applications with Node.js and WebSockets
Strategies for developing real-time applications using Node.js and WebSockets to enable instant data exchange and interactive user experiences.
0 likes
326 views
Rule Content
title: Building Real-Time Applications with Node.js and WebSockets
description: Strategies for developing real-time applications using Node.js and WebSockets to enable instant data exchange and interactive user experiences.
category: Node.js Cursor Rules
rules:
- name: use_native_websocket_client
description: Utilize Node.js's built-in WebSocket client for real-time communication to reduce dependencies and align with modern web standards.
filters:
- type: node_version
pattern: ">=21.0.0"
actions:
- type: suggest
message: |
Node.js v21 and later include a native WebSocket client, eliminating the need for external libraries. This built-in client simplifies real-time communication and ensures better interoperability. For example:
```javascript
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', () => {
console.log('Connected to server');
socket.send('Hello Server!');
});
socket.addEventListener('message', (event) => {
console.log('Message from server:', event.data);
});
```
Ensure your Node.js version is up to date to leverage this feature.
references:
- https://nodejs.org/en/learn/getting-started/websocket
- name: secure_websocket_connections
description: Implement SSL/TLS to secure WebSocket connections and protect data integrity.
filters:
- type: file_content
pattern: "new WebSocket\\('ws://"
actions:
- type: suggest
message: |
To secure WebSocket connections, use the 'wss://' protocol with SSL/TLS encryption. This ensures data transmitted over the connection is encrypted and secure from eavesdropping or tampering. For example:
```javascript
const fs = require('fs');
const https = require('https');
const WebSocket = require('ws');
const server = https.createServer({
key: fs.readFileSync('path/to/private-key.pem'),
cert: fs.readFileSync('path/to/certificate.pem')
});
const wss = new WebSocket.Server({ server });
server.listen(8080, () => {
console.log('Secure WebSocket server is running on port 8080');
});
```
Ensure you have valid SSL/TLS certificates configured for your domain.
references:
- https://medium.com/@innovativejude.tech/how-to-secure-websocket-connections-in-node-js-a-step-by-step-guide-6d983a07bd96
- name: handle_websocket_errors
description: Implement comprehensive error handling for WebSocket connections to maintain application stability.
filters:
- type: file_content
pattern: "new WebSocket\\("
actions:
- type: suggest
message: |
Always include error handling logic for WebSocket connections to manage potential disconnections or message failures. For example:
```javascript
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('error', (error) => {
console.error('WebSocket error:', error);
});
socket.addEventListener('close', (event) => {
console.log('WebSocket connection closed:', event.code, event.reason);
});
```
Proper error handling ensures a better user experience and aids in troubleshooting issues.
references:
- https://infinitejs.com/posts/avoiding-pitfalls-nodejs-websocket-chat/
- name: implement_heartbeat_mechanism
description: Use heartbeat mechanisms to detect and manage inactive WebSocket connections.
filters:
- type: file_content
pattern: "new WebSocket\\("
actions:
- type: suggest
message: |
Implement a heartbeat or ping/pong mechanism to detect and manage inactive WebSocket connections. This helps maintain connection stability and detect dropped connections. For example:
```javascript
const sendHeartbeat = (ws) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'heartbeat' }));
}
};
setInterval(() => {
wss.clients.forEach(sendHeartbeat);
}, 30000); // Send a heartbeat every 30 seconds
```
This practice ensures that both client and server are aware of the connection's status.
references:
- https://infinitejs.com/posts/avoiding-websocket-pitfalls-nodejs-chat/
- name: validate_incoming_messages
description: Validate and sanitize incoming WebSocket messages to prevent security vulnerabilities.
filters:
- type: file_content
pattern: "ws\\.on\\('message',"
actions:
- type: suggest
message: |
Always validate and sanitize incoming WebSocket messages to prevent security vulnerabilities. For example:
```javascript
ws.on('message', (message) => {
try {
const data = JSON.parse(message);
// Validate data structure and content here
} catch (error) {
console.error('Invalid message received:', error);
ws.close(1008, 'Invalid message format');
}
});
```
Proper validation ensures that only well-formed and expected data is processed by your application.
references:
- https://infinitejs.com/posts/avoiding-websocket-pitfalls-nodejs-chat/