mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+335
-298
@@ -1,302 +1,339 @@
|
||||
---
|
||||
description: This rule provides guidelines and best practices for developing robust, scalable, and secure real-time applications using Socket.IO. It covers code organization, performance optimization, security considerations, testing strategies, and common pitfalls to avoid when working with Socket.IO.
|
||||
globs: *.js,*.ts,*.jsx,*.tsx
|
||||
description: Definitive guidelines for building robust, performant, and maintainable real-time applications using Socket.IO v4.x, emphasizing modern JavaScript practices and common pitfalls.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
# Socket.IO Best Practices
|
||||
|
||||
This document outlines best practices for developing robust, scalable, and secure real-time applications using Socket.IO. It covers various aspects, from code organization to security considerations.
|
||||
|
||||
## Library Information:
|
||||
- Name: socket-io
|
||||
- Tags: websockets, real-time, javascript, communication
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
A well-organized codebase is crucial for maintainability and scalability. For Socket.IO projects, consider the following structure:
|
||||
|
||||
|
||||
project-root/
|
||||
├── node_modules/
|
||||
├── src/
|
||||
│ ├── app.ts (or app.js) # Main application entry point
|
||||
│ ├── config/ # Configuration files
|
||||
│ │ └── socket.ts # Socket.IO configuration
|
||||
│ ├── socket/ # Socket event handlers and logic
|
||||
│ │ ├── index.ts # Centralized socket connection and event handling
|
||||
│ │ ├── events/ # Directory for different socket event modules
|
||||
│ │ │ ├── chat.ts # Chat-related events
|
||||
│ │ │ ├── notifications.ts # Notification-related events
|
||||
│ │ │ └── ... # Other event modules
|
||||
│ │ ├── middleware/ # Socket.IO middleware for authentication, etc.
|
||||
│ │ │ └── auth.ts # Example authentication middleware
|
||||
│ │ └── utils/ # Utility functions for socket operations
|
||||
│ ├── models/ # Data models
|
||||
│ ├── services/ # Business logic services
|
||||
│ ├── utils/ # Utility functions
|
||||
│ ├── types/ # TypeScript type definitions
|
||||
│ └── public/ # Static assets (if applicable)
|
||||
├── tests/ # Unit and integration tests
|
||||
├── .env # Environment variables
|
||||
├── package.json # Project dependencies and scripts
|
||||
├── tsconfig.json # TypeScript configuration (if using TypeScript)
|
||||
└── README.md # Project documentation
|
||||
|
||||
|
||||
### File Naming Conventions
|
||||
|
||||
* Use descriptive names for files and directories.
|
||||
* Follow a consistent naming convention (e.g., `camelCase` or `kebab-case`).
|
||||
* For TypeScript projects, use `.ts` for source files and `.d.ts` for declaration files.
|
||||
|
||||
### Module Organization
|
||||
|
||||
* Break down your application into smaller, modular components.
|
||||
* Use ES modules (import/export) or CommonJS (require) for module organization.
|
||||
* Consider using a dependency injection container for managing dependencies.
|
||||
|
||||
### Component Architecture
|
||||
|
||||
* Adopt a component-based architecture to promote reusability and separation of concerns.
|
||||
* Create reusable components for common Socket.IO tasks, such as message handling or authentication.
|
||||
* Utilize design patterns like the Observer pattern for managing socket events.
|
||||
|
||||
### Code Splitting
|
||||
|
||||
* For large applications, consider using code splitting to reduce the initial bundle size.
|
||||
* Load socket event handlers on demand when they are needed.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### Design Patterns
|
||||
|
||||
* **Observer Pattern:** Used extensively in Socket.IO to manage real-time updates.
|
||||
* **Factory Pattern:** Create socket instances and event handlers.
|
||||
* **Middleware Pattern:** Implement authentication, authorization, and data validation.
|
||||
|
||||
### Recommended Approaches
|
||||
|
||||
* Use a class-based approach to encapsulate socket-related logic.
|
||||
* Organize your code into namespaces and rooms to manage different parts of your application effectively.
|
||||
* Implement automatic reconnection and handle disconnections gracefully.
|
||||
* Use heartbeats to maintain active connections.
|
||||
|
||||
### Anti-patterns
|
||||
|
||||
* **Global Socket Instance:** Avoid using a global socket instance. Instead, pass the socket instance to the relevant components.
|
||||
* **Overly Complex Event Handlers:** Keep event handlers small and focused. Delegate complex logic to separate functions or services.
|
||||
* **Ignoring Errors:** Always handle errors properly and log them for debugging purposes.
|
||||
* **Sending Large Payloads:** Avoid sending large payloads over Socket.IO. Optimize your data structures and compress data if necessary.
|
||||
* **Tight Coupling:** Avoid tight coupling between your socket event handlers and your application logic. Use dependency injection or other techniques to decouple your code.
|
||||
|
||||
### State Management
|
||||
|
||||
* Use a centralized state management solution (e.g., Redux, Zustand, or a simple in-memory store) to manage the state of your Socket.IO application.
|
||||
* Keep the state synchronized between the client and the server.
|
||||
* Use immutable data structures to simplify state management and prevent unexpected side effects.
|
||||
|
||||
### Error Handling
|
||||
|
||||
* Use try-catch blocks to handle synchronous errors.
|
||||
* Use promise rejections to handle asynchronous errors.
|
||||
* Implement a global error handler to catch unhandled exceptions.
|
||||
* Log all errors to a file or a monitoring service.
|
||||
* Consider using a circuit breaker pattern to prevent cascading failures.
|
||||
* Inform the client about errors in a user-friendly way.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### Optimization Techniques
|
||||
|
||||
* Minimize data transmission size and frequency.
|
||||
* Use data compression techniques (e.g., gzip or brotli) to reduce payload sizes.
|
||||
* Optimize message payloads (e.g., use binary data instead of JSON strings).
|
||||
* Use namespaces and rooms to target messages to specific clients.
|
||||
* Implement pagination or filtering to reduce the amount of data sent to the client.
|
||||
|
||||
### Memory Management
|
||||
|
||||
* Monitor memory usage and identify memory leaks.
|
||||
* Use garbage collection to reclaim unused memory.
|
||||
* Avoid creating large objects in memory.
|
||||
* Use streams to process large data sets.
|
||||
|
||||
### Rendering Optimization
|
||||
|
||||
* Use virtual DOM techniques to minimize DOM updates.
|
||||
* Batch DOM updates to improve performance.
|
||||
* Use CSS transforms and animations instead of JavaScript animations.
|
||||
|
||||
### Bundle Size Optimization
|
||||
|
||||
* Use a bundler (e.g., Webpack, Parcel, or Rollup) to optimize your JavaScript bundles.
|
||||
* Minify and compress your JavaScript code.
|
||||
* Remove unused code (dead code elimination).
|
||||
* Use code splitting to load code on demand.
|
||||
|
||||
### Lazy Loading
|
||||
|
||||
* Load socket event handlers on demand when they are needed.
|
||||
* Lazy load images and other assets.
|
||||
* Use dynamic imports to load modules on demand.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### Common Vulnerabilities
|
||||
|
||||
* **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input and encoding output.
|
||||
* **SQL Injection:** Prevent SQL injection attacks by using parameterized queries or an ORM.
|
||||
* **Denial-of-Service (DoS):** Prevent DoS attacks by limiting request rates and using a CDN.
|
||||
* **Man-in-the-Middle (MitM):** Prevent MitM attacks by using HTTPS and validating SSL/TLS certificates.
|
||||
* **Unauthorized Access:** Prevent unauthorized access by implementing proper authentication and authorization mechanisms.
|
||||
|
||||
### Input Validation
|
||||
|
||||
* Validate all incoming data on the server-side.
|
||||
* Use a schema validation library (e.g., Joi or Yup) to define and enforce data schemas.
|
||||
* Sanitize user input to prevent XSS attacks.
|
||||
* Escape special characters to prevent SQL injection attacks.
|
||||
|
||||
### Authentication and Authorization
|
||||
|
||||
* Use a strong authentication mechanism (e.g., JSON Web Tokens (JWT) or OAuth 2.0).
|
||||
* Implement role-based access control (RBAC) to restrict access to sensitive resources.
|
||||
* Use HTTPS to protect authentication credentials in transit.
|
||||
* Store passwords securely using a hashing algorithm (e.g., bcrypt).
|
||||
* Implement two-factor authentication (2FA) for enhanced security.
|
||||
* Use Socket.IO middleware to authenticate users before allowing them to connect.
|
||||
|
||||
### Data Protection
|
||||
|
||||
* Encrypt sensitive data at rest and in transit.
|
||||
* Use a strong encryption algorithm (e.g., AES-256).
|
||||
* Store encryption keys securely.
|
||||
* Implement data masking to protect sensitive data from unauthorized access.
|
||||
* Comply with relevant data privacy regulations (e.g., GDPR or CCPA).
|
||||
|
||||
### Secure API Communication
|
||||
|
||||
* Use HTTPS for all API communication.
|
||||
* Validate SSL/TLS certificates.
|
||||
* Implement rate limiting to prevent DoS attacks.
|
||||
* Use API keys or tokens to authenticate API requests.
|
||||
* Log all API requests and responses for auditing purposes.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### Unit Testing
|
||||
|
||||
* Write unit tests for individual components and functions.
|
||||
* Use a testing framework (e.g., Jest, Mocha, or Jasmine).
|
||||
* Mock dependencies to isolate the component being tested.
|
||||
* Test edge cases and error conditions.
|
||||
* Aim for high code coverage.
|
||||
|
||||
### Integration Testing
|
||||
|
||||
* Write integration tests to verify that different parts of your application work together correctly.
|
||||
* Test the interaction between Socket.IO clients and the server.
|
||||
* Use a testing framework (e.g., Supertest or Cypress).
|
||||
* Set up a test environment that mimics the production environment.
|
||||
|
||||
### End-to-End Testing
|
||||
|
||||
* Write end-to-end tests to simulate real-world user scenarios.
|
||||
* Use a testing framework (e.g., Selenium, Puppeteer, or Cypress).
|
||||
* Test the entire application stack, from the client to the database.
|
||||
* Test performance and scalability under load.
|
||||
|
||||
### Test Organization
|
||||
|
||||
* Organize your tests in a separate directory (e.g., `tests`).
|
||||
* Use a consistent naming convention for test files.
|
||||
* Group tests by component or feature.
|
||||
* Write clear and concise test descriptions.
|
||||
|
||||
### Mocking and Stubbing
|
||||
|
||||
* Use mocking and stubbing to isolate components and simplify testing.
|
||||
* Use a mocking library (e.g., Sinon.js or Jest's built-in mocking capabilities).
|
||||
* Mock external dependencies, such as databases or APIs.
|
||||
* Stub functions to control their behavior during testing.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### Frequent Mistakes
|
||||
|
||||
* Forgetting to handle disconnections gracefully.
|
||||
* Not validating user input.
|
||||
* Not securing WebSocket connections.
|
||||
* Using a global socket instance.
|
||||
* Overly complex event handlers.
|
||||
* Ignoring errors.
|
||||
* Sending large payloads.
|
||||
* Tight coupling.
|
||||
* Not monitoring memory usage.
|
||||
* Not testing the application thoroughly.
|
||||
|
||||
### Edge Cases
|
||||
|
||||
* Handling network interruptions and reconnections.
|
||||
* Dealing with slow or unreliable connections.
|
||||
* Managing multiple concurrent connections.
|
||||
* Handling large data sets.
|
||||
* Dealing with different browser implementations of WebSockets.
|
||||
|
||||
### Version-Specific Issues
|
||||
|
||||
* Be aware of breaking changes between Socket.IO versions.
|
||||
* Consult the Socket.IO changelog for information about version-specific issues.
|
||||
* Test your application thoroughly after upgrading Socket.IO.
|
||||
|
||||
### Compatibility Concerns
|
||||
|
||||
* Ensure that your Socket.IO client and server versions are compatible.
|
||||
* Be aware of compatibility issues between Socket.IO and other technologies, such as load balancers or firewalls.
|
||||
|
||||
### Debugging Strategies
|
||||
|
||||
* Use the Socket.IO client and server debug logs to troubleshoot issues.
|
||||
* Use browser developer tools to inspect WebSocket traffic.
|
||||
* Use a network monitoring tool (e.g., Wireshark) to capture and analyze network packets.
|
||||
* Use a code debugger (e.g., VS Code's built-in debugger) to step through your code and inspect variables.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### Recommended Tools
|
||||
|
||||
* **Code Editor:** VS Code, Sublime Text, or Atom
|
||||
* **Testing Framework:** Jest, Mocha, or Jasmine
|
||||
* **Bundler:** Webpack, Parcel, or Rollup
|
||||
* **Linting and Formatting:** ESLint and Prettier
|
||||
* **Network Monitoring:** Wireshark
|
||||
* **Load Testing:** Apache JMeter or Artillery
|
||||
|
||||
### Build Configuration
|
||||
|
||||
* Use a build tool (e.g., Webpack or Parcel) to automate the build process.
|
||||
* Configure your build tool to minify and compress your JavaScript code.
|
||||
* Use environment variables to configure your application for different environments (e.g., development, testing, and production).
|
||||
|
||||
### Linting and Formatting
|
||||
|
||||
* Use a linter (e.g., ESLint) to enforce code style and identify potential errors.
|
||||
* Use a code formatter (e.g., Prettier) to automatically format your code.
|
||||
* Configure your linter and formatter to work together seamlessly.
|
||||
* Use a Git hook to run your linter and formatter before committing code.
|
||||
|
||||
### Deployment Best Practices
|
||||
|
||||
* Use a process manager (e.g., PM2 or Nodemon) to manage your Node.js application.
|
||||
* Deploy your application to a cloud platform (e.g., AWS, Azure, or Google Cloud).
|
||||
* Use a load balancer to distribute traffic across multiple servers.
|
||||
* Use a CDN to serve static assets.
|
||||
* Monitor your application's performance and uptime.
|
||||
|
||||
### CI/CD Integration
|
||||
|
||||
* Use a CI/CD pipeline to automate the build, test, and deployment process.
|
||||
* Use a CI/CD tool (e.g., Jenkins, Travis CI, or CircleCI).
|
||||
* Run unit tests, integration tests, and end-to-end tests as part of your CI/CD pipeline.
|
||||
* Automate the deployment process to reduce the risk of human error.
|
||||
|
||||
By following these best practices, you can develop robust, scalable, and secure real-time applications using Socket.IO. Remember to adapt these guidelines to your specific project requirements and context.
|
||||
Socket.IO v4.x is the bedrock for real-time communication in our applications. This guide establishes the definitive standards for its usage, focusing on reliability, performance, and maintainability.
|
||||
|
||||
## 1. Core Initialization & Security
|
||||
|
||||
Always initialize Socket.IO clients with explicit, secure, and efficient options.
|
||||
|
||||
### ✅ GOOD: Secure & Explicit Client Initialization
|
||||
Use `wss://` in production, enable CORS on the server for cross-origin clients, and avoid `forceNew` unless strictly necessary.
|
||||
|
||||
```javascript
|
||||
// client.js
|
||||
import { io } from "socket.io-client";
|
||||
|
||||
// For production, always use wss://
|
||||
const socket = io("wss://api.yourdomain.com", {
|
||||
path: "/socket.io/", // Explicitly define path if customized on server
|
||||
transports: ["websocket", "polling"], // Prefer WebSocket, fallback to polling
|
||||
autoConnect: true, // Connect automatically
|
||||
auth: {
|
||||
token: "YOUR_AUTH_TOKEN", // Pass authentication data
|
||||
},
|
||||
query: {
|
||||
// Additional query parameters
|
||||
clientId: "unique-client-id",
|
||||
},
|
||||
});
|
||||
|
||||
// Server-side (Node.js with Express)
|
||||
// Ensure CORS is correctly configured for your client origin
|
||||
const express = require("express");
|
||||
const http = require("http");
|
||||
const { Server } = require("socket.io");
|
||||
|
||||
const app = express();
|
||||
const server = http.createServer(app);
|
||||
const ioServer = new Server(server, {
|
||||
cors: {
|
||||
origin: "https://yourclientdomain.com", // Your client's domain
|
||||
methods: ["GET", "POST"],
|
||||
credentials: true,
|
||||
},
|
||||
path: "/socket.io/", // Match client path
|
||||
});
|
||||
|
||||
ioServer.on("connection", (socket) => {
|
||||
// Access auth token: socket.handshake.auth.token
|
||||
// Access query params: socket.handshake.query.clientId
|
||||
console.log(`Client connected: ${socket.id}`);
|
||||
});
|
||||
```
|
||||
|
||||
### ❌ BAD: Insecure or Inefficient Initialization
|
||||
Avoid `http://` in production, implicit options, and unnecessary `forceNew`.
|
||||
|
||||
```javascript
|
||||
// client.js
|
||||
// ❌ Insecure in production, relies on implicit defaults
|
||||
const socket = io("http://localhost:3000");
|
||||
|
||||
// ❌ Creates a new underlying connection even if one exists for the same URL,
|
||||
// wasting resources unless specifically required for isolation.
|
||||
const anotherSocket = io("https://api.yourdomain.com", { forceNew: true });
|
||||
```
|
||||
|
||||
## 2. Code Organization: Namespaces & Rooms
|
||||
|
||||
Structure your real-time logic using namespaces and rooms to isolate concerns and manage communication efficiently.
|
||||
|
||||
### ✅ GOOD: Logical Separation with Namespaces and Rooms
|
||||
Use namespaces for distinct application features (e.g., `/chat`, `/admin`) and rooms for grouping clients within a namespace (e.g., `roomId: 'general'`, `userId: 'user123'`).
|
||||
|
||||
```javascript
|
||||
// Server-side
|
||||
const chatNamespace = ioServer.of("/chat");
|
||||
chatNamespace.use((socket, next) => {
|
||||
// Namespace-specific authentication/authorization
|
||||
if (socket.handshake.auth.token === "valid-chat-token") {
|
||||
next();
|
||||
} else {
|
||||
next(new Error("Authentication error for chat namespace"));
|
||||
}
|
||||
});
|
||||
|
||||
chatNamespace.on("connection", (socket) => {
|
||||
console.log(`User ${socket.id} connected to /chat`);
|
||||
|
||||
socket.on("joinRoom", (roomName) => {
|
||||
socket.join(roomName);
|
||||
socket.emit("roomJoined", `You joined ${roomName}`);
|
||||
chatNamespace.to(roomName).emit("userJoined", `${socket.id} joined ${roomName}`);
|
||||
});
|
||||
|
||||
socket.on("sendMessage", ({ room, message }) => {
|
||||
chatNamespace.to(room).emit("newMessage", { user: socket.id, message });
|
||||
});
|
||||
});
|
||||
|
||||
// Client-side
|
||||
const chatSocket = io("wss://api.yourdomain.com/chat", {
|
||||
auth: { token: "valid-chat-token" },
|
||||
});
|
||||
chatSocket.on("connect", () => {
|
||||
chatSocket.emit("joinRoom", "general");
|
||||
});
|
||||
chatSocket.on("newMessage", (data) => console.log("New chat message:", data));
|
||||
```
|
||||
|
||||
### ❌ BAD: Monolithic Event Handling
|
||||
Avoid dumping all events into the default namespace without logical grouping.
|
||||
|
||||
```javascript
|
||||
// Server-side
|
||||
// ❌ All events mixed in the root namespace, hard to manage access and scale
|
||||
ioServer.on("connection", (socket) => {
|
||||
socket.on("chatMessage", () => {
|
||||
/* ... */
|
||||
});
|
||||
socket.on("adminAction", () => {
|
||||
/* ... */
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## 3. Robust Error Handling & Reconnection
|
||||
|
||||
Socket.IO provides automatic reconnection, but you must handle connection errors and customize retry strategies for production.
|
||||
|
||||
### ✅ GOOD: Comprehensive Error & Reconnection Handling
|
||||
Listen for `connect_error` to diagnose issues and `reconnect_attempt` to customize back-off strategies.
|
||||
|
||||
```javascript
|
||||
// Client-side
|
||||
socket.on("connect_error", (err) => {
|
||||
console.error("Connection error:", err.message);
|
||||
// Implement custom exponential back-off if needed, though Socket.IO has defaults
|
||||
if (err.message === "Authentication error") {
|
||||
console.error("Authentication failed, stopping reconnection attempts.");
|
||||
socket.disconnect(); // Stop trying to reconnect if auth permanently fails
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("reconnect_attempt", (attemptNumber) => {
|
||||
console.log(`Reconnection attempt ${attemptNumber}`);
|
||||
// Dynamically adjust query parameters or auth tokens if necessary
|
||||
// socket.io.opts.query = { newAuthToken: "..." };
|
||||
});
|
||||
|
||||
socket.on("reconnect", (attemptNumber) => {
|
||||
console.log(`Reconnected after ${attemptNumber} attempts.`);
|
||||
});
|
||||
|
||||
socket.on("disconnect", (reason) => {
|
||||
console.log("Disconnected:", reason);
|
||||
if (reason === "io server disconnect") {
|
||||
// The server has forcefully disconnected the client,
|
||||
// do not attempt to reconnect automatically.
|
||||
// Instead, prompt user or log for investigation.
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### ❌ BAD: Ignoring Connection State
|
||||
Neglecting error events leads to silent failures and poor user experience.
|
||||
|
||||
```javascript
|
||||
// Client-side
|
||||
// ❌ No error handling, user won't know if connection fails
|
||||
socket.on("connect", () => console.log("Connected"));
|
||||
// ... no other connection-related event listeners
|
||||
```
|
||||
|
||||
## 4. Payload Hygiene & Acknowledgements
|
||||
|
||||
Keep payloads lean, avoid circular references, and use acknowledgements for critical data delivery guarantees.
|
||||
|
||||
### ✅ GOOD: Efficient Payloads & Guaranteed Delivery
|
||||
Send only necessary data. For critical operations, use acknowledgements.
|
||||
|
||||
```javascript
|
||||
// Client-side
|
||||
socket.emit("createOrder", { productId: "P123", quantity: 2 }, (response) => {
|
||||
if (response.success) {
|
||||
console.log("Order created successfully:", response.orderId);
|
||||
} else {
|
||||
console.error("Failed to create order:", response.error);
|
||||
}
|
||||
});
|
||||
|
||||
// Server-side
|
||||
ioServer.on("connection", (socket) => {
|
||||
socket.on("createOrder", (orderData, callback) => {
|
||||
try {
|
||||
// Process orderData, ensure it's clean and valid
|
||||
const newOrder = processOrder(orderData); // Avoid circular references here
|
||||
callback({ success: true, orderId: newOrder.id }); // Acknowledge with result
|
||||
} catch (error) {
|
||||
callback({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### ❌ BAD: Bloated Payloads & Unreliable Delivery
|
||||
Sending large, unoptimized data or assuming delivery for critical actions.
|
||||
|
||||
```javascript
|
||||
// Client-side
|
||||
// ❌ Sending an entire complex object graph, potentially with circular references
|
||||
const userSession = { /* ... large object ... */ };
|
||||
socket.emit("updateSession", userSession); // No acknowledgement, delivery not guaranteed
|
||||
|
||||
// Server-side
|
||||
ioServer.on("connection", (socket) => {
|
||||
socket.on("updateSession", (sessionData) => {
|
||||
// ❌ If sessionData has circular references, this will crash
|
||||
JSON.stringify(sessionData);
|
||||
// ... no callback for client to confirm update
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## 5. Performance & Scalability
|
||||
|
||||
Optimize for network efficiency and design for horizontal scaling.
|
||||
|
||||
### ✅ GOOD: Minimal Data & Scalable Design
|
||||
Send only deltas, use binary for large data, and consider a Redis adapter for multi-server deployments.
|
||||
|
||||
```javascript
|
||||
// Client-side (sending binary data)
|
||||
const imageBuffer = new ArrayBuffer(1024); // Example binary data
|
||||
socket.emit("uploadImage", imageBuffer);
|
||||
|
||||
// Server-side (using Redis adapter for scalability)
|
||||
const { createAdapter } = require("@socket.io/redis-adapter");
|
||||
const { createClient } = require("redis");
|
||||
|
||||
const pubClient = createClient({ url: "redis://localhost:6379" });
|
||||
const subClient = pubClient.duplicate();
|
||||
|
||||
Promise.all([pubClient.connect(), subClient.connect()]).then(() => {
|
||||
ioServer.adapter(createAdapter(pubClient, subClient));
|
||||
// Now events can be broadcast across multiple Socket.IO servers
|
||||
ioServer.emit("globalEvent", "This reaches all clients across all servers");
|
||||
});
|
||||
```
|
||||
|
||||
### ❌ BAD: Inefficient Data Transfer & Monolithic Servers
|
||||
Sending full state updates repeatedly or running a single server without an adapter for high-traffic scenarios.
|
||||
|
||||
```javascript
|
||||
// Client-side
|
||||
// ❌ Sending entire game state every frame instead of just changes
|
||||
const gameState = { /* ... huge object ... */ };
|
||||
setInterval(() => {
|
||||
socket.emit("gameStateUpdate", gameState);
|
||||
}, 16); // 60 FPS
|
||||
|
||||
// Server-side
|
||||
// ❌ No adapter for scaling, only works for a single server instance
|
||||
// ioServer.emit("globalEvent", "This only reaches clients on THIS server");
|
||||
```
|
||||
|
||||
## 6. Type Safety with TypeScript
|
||||
|
||||
Always use TypeScript to define clear contracts for events and payloads, preventing runtime errors.
|
||||
|
||||
### ✅ GOOD: Strongly Typed Event Definitions
|
||||
Define interfaces for event names and their corresponding payloads.
|
||||
|
||||
```typescript
|
||||
// types/socket.ts
|
||||
export interface ServerToClientEvents {
|
||||
noArg: () => void;
|
||||
basicEmit: (a: number, b: string, c: Buffer) => void;
|
||||
withAck: (d: string, callback: (e: number) => void) => void;
|
||||
roomJoined: (roomName: string) => void;
|
||||
newMessage: (data: { user: string; message: string }) => void;
|
||||
}
|
||||
|
||||
export interface ClientToServerEvents {
|
||||
hello: () => void;
|
||||
createOrder: (orderData: { productId: string; quantity: number }, callback: (response: { success: boolean; orderId?: string; error?: string }) => void) => void;
|
||||
joinRoom: (roomName: string) => void;
|
||||
sendMessage: (data: { room: string; message: string }) => void;
|
||||
}
|
||||
|
||||
export interface InterServerEvents {
|
||||
ping: () => void;
|
||||
}
|
||||
|
||||
export interface SocketData {
|
||||
userId: string;
|
||||
foo: string;
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// server.ts
|
||||
import { Server } from "socket.io";
|
||||
import { ClientToServerEvents, ServerToClientEvents, InterServerEvents, SocketData } from "./types/socket";
|
||||
|
||||
const ioServer = new Server<ClientToServerEvents, ServerToClientEvents, InterServerEvents, SocketData>(3000);
|
||||
|
||||
ioServer.on("connection", (socket) => {
|
||||
socket.data.userId = "abc"; // Type-safe socket data
|
||||
socket.on("createOrder", (orderData, callback) => {
|
||||
console.log(orderData.productId); // Autocomplete and type checking
|
||||
callback({ success: true, orderId: "ORD123" });
|
||||
});
|
||||
});
|
||||
|
||||
// client.ts
|
||||
import { io, Socket } from "socket.io-client";
|
||||
import { ClientToServerEvents, ServerToClientEvents } from "./types/socket";
|
||||
|
||||
const socket: Socket<ServerToClientEvents, ClientToServerEvents> = io("wss://api.yourdomain.com");
|
||||
|
||||
socket.on("roomJoined", (roomName) => {
|
||||
console.log(`Joined room: ${roomName}`); // Type-safe event listener
|
||||
});
|
||||
|
||||
socket.emit("createOrder", { productId: "P456", quantity: 1 }, (response) => {
|
||||
if (response.success) {
|
||||
console.log(response.orderId); // Type-safe response
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### ❌ BAD: Untyped Events
|
||||
Using plain JavaScript or `any` types for events, leading to potential runtime errors and difficult debugging.
|
||||
|
||||
```javascript
|
||||
Reference in New Issue
Block a user