What are Socket.io best practices for production?
Use WebSocket transport only, Redis adapter for scaling, PM2 cluster mode, JWT auth, input validation, rate limiting, clean up on disconnect, limit message size, monitor connections and memory, handle memory leaks, use acknowledgments, rejoin rooms on reconnect, and HTTPS/WSS only.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Socket.io Summary and Complete Guide Real-Time Node.js Applications
Install socket.io, create HTTP server from Express, initialize socketio with CORS and WebSocket transport, add JWT auth middleware, handle connection/disconnection, track online users, manage rooms with deterministic IDs, handle events (message, typing, presence), add Redis adapter for scaling, use PM2 cluster mode, and configure Nginx with WebSocket proxy headers.
Use the Redis adapter (@socket.io/redis-adapter) for cross-instance message broadcasting, PM2 cluster mode (instances: 'max', exec_mode: 'cluster'), Nginx with ip_hash for sticky sessions, and WebSocket proxy headers (Upgrade, Connection). Monitor connection count and memory usage.
Use io.use() middleware: read token from socket.handshake.auth.token, verify with jwt.verify(), find the user, attach to socket.user. The client passes the token in the auth option: io(url, { auth: { token } }). Handle connect_error for auth failures and redirect to login.
Still have questions?
Browse all our FAQs or reach out to our support team
