Implement WebSocket server with rooms
✓Works with OpenClaudeYou are a Node.js backend engineer. The user wants to implement a WebSocket server with room-based communication using Socket.IO.
What to check first
- Verify Node.js is installed:
node --version(v14+) - Check if Socket.IO is in package.json:
npm list socket.io - Confirm an HTTP server package exists:
npm list expressornpm list http
Steps
- Install Socket.IO:
npm install socket.io(also neednpm install expressfor the HTTP server) - Create an Express server and attach Socket.IO to it using
http.createServer(app) - Initialize Socket.IO with the server instance:
const io = require('socket.io')(httpServer) - Listen for the
connectionevent on the io instance to handle new socket connections - Inside the connection handler, use
socket.on('join', callback)to handle room join requests with the room name parameter - Use
socket.join(roomName)to add the socket to a room - Broadcast messages to a specific room using
io.to(roomName).emit(eventName, data) - Handle disconnection with
socket.on('disconnect')and optionally usesocket.leave(roomName)before cleanup
Code
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIO(server, {
cors: {
origin: '*',
methods: ['GET', 'POST']
}
});
const PORT = process.env.PORT || 3000;
// Track room members
const rooms = {};
io.on('connection', (socket) => {
console.log(`User connected: ${socket.id}`);
// Handle joining a room
socket.on('join', (roomName, userName) => {
socket.join(roomName);
socket.currentRoom = roomName;
socket.userName = userName;
if (!rooms[roomName]) {
rooms[roomName] = [];
}
rooms[roomName].push({ id: socket.id, name: userName });
// Notify others in the room
io.to(roomName).emit('user-joined', {
userName: userName,
userId: socket.id,
totalUsers: rooms[roomName].length
});
// Send room state to the joining user
socket.emit('room-state', {
members: rooms[roomName],
roomName: roomName
});
});
// Handle messages in a room
socket.on('message', (msg) => {
if (socket.currentRoom) {
io.to(socket.currentRoom).emit('new-message', {
userId: socket.id,
userName: socket.userName,
text: msg,
timestamp: new Date
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Backend Skills
Other Claude Code skills in the same category — free to download.
Express Setup
Scaffold Express.js app with best practices
Fastify Setup
Scaffold Fastify app with plugins
NestJS Module
Generate NestJS modules, controllers, services
Middleware Chain
Create and organize middleware chain
Queue Worker
Set up job queue with Bull/BullMQ
File Upload Handler
Create file upload handling with validation
Email Service
Set up transactional email service
Cron Job Setup
Set up scheduled cron jobs
Want a Backend skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.