Your First Socket.IO Server
Building your first Socket.IO server involves three pieces: an HTTP server (usually via Express), a Socket.IO server instance attached to it, and event handlers registered inside the 'connection' event, which fires once per client that successfully connects. Every connected client is represented server-side as a 'socket' object with a unique 'id', and all event listeners you attach for that client -- custom events, 'disconnect', errors -- go inside that connection callback.
Cricket analogy: It's like a stadium's turnstile system logging each fan's entry with a unique ticket ID the moment they walk in, similar to how the 'connection' event fires once per client with a unique socket.id.
Setting Up the Server
Start by creating an Express app and wrapping it with Node's http.createServer, since Socket.IO needs the raw HTTP server object (not the Express app directly) to attach its upgrade handler. Then instantiate 'new Server(httpServer, options)', configuring CORS if your frontend runs on a different port during development. Finally, call httpServer.listen(port) -- not app.listen(port) -- so both regular HTTP routes and Socket.IO's WebSocket upgrade requests are served from the same underlying server.
Cricket analogy: It's like routing both the TV broadcast feed and the radio commentary feed through the same central production truck rather than two separate trucks, similar to httpServer.listen() serving both HTTP and Socket.IO traffic.
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const httpServer = http.createServer(app);
const io = new Server(httpServer, {
cors: { origin: 'http://localhost:5173', methods: ['GET', 'POST'] },
});
app.get('/health', (req, res) => res.send('ok'));
io.on('connection', (socket) => {
console.log(`Client connected: ${socket.id}`);
socket.on('joinRoom', (roomName) => {
socket.join(roomName);
io.to(roomName).emit('systemMessage', `${socket.id} joined ${roomName}`);
});
socket.on('disconnect', (reason) => {
console.log(`Client disconnected: ${socket.id}, reason: ${reason}`);
});
});
httpServer.listen(3000, () => console.log('Listening on port 3000'));Handling Connections and Custom Events
Inside the 'connection' callback, use socket.on(eventName, handler) to react to events the client emits, and socket.emit(eventName, data) to send data back to just that one client. To send to everyone, use io.emit(...); to send to everyone except the sender, use socket.broadcast.emit(...); to target a subset, use socket.join(roomName) followed by io.to(roomName).emit(...). Always register a 'disconnect' listener too, since cleaning up any per-client state (like removing them from an in-memory room list) typically needs to happen there.
Cricket analogy: It's like a stadium PA distinguishing between a message to one specific box (socket.emit), an announcement to the whole crowd (io.emit), and an announcement to everyone except the person who just reported the issue (socket.broadcast.emit).
Forgetting to configure CORS correctly is one of the most common first-server mistakes: if your frontend runs on a different origin (e.g., localhost:5173) than your Socket.IO server (e.g., localhost:3000), you must set the 'cors' option in 'new Server(httpServer, { cors: { origin: ... } })', or the browser will block the connection.
- A Socket.IO server needs an HTTP server instance, a Server object attached to it, and 'connection' event handlers.
- Call httpServer.listen(), not app.listen(), so both HTTP and Socket.IO traffic share the same server.
- Each connected client gets a unique socket.id and its own socket object inside the 'connection' callback.
- Use socket.emit for one client, io.emit for everyone, socket.broadcast.emit for everyone except the sender, and rooms for targeted subsets.
- Always handle 'disconnect' to clean up any per-client state.
- Configure the 'cors' option whenever frontend and backend run on different origins.
Practice what you learned
1. Which method should you call to start listening when using Socket.IO with Express?
2. What event fires on the server once per client that successfully connects?
3. Which emit sends data to everyone except the client that triggered the event?
4. What is the standard pattern to broadcast to a targeted subset of clients?
5. Why is a 'disconnect' handler important in a Socket.IO server?
Was this page helpful?
You May Also Like
Installing and Setup
How to install the Socket.IO server and client packages, wire them into an existing Node.js/Express project, and avoid common version-mismatch pitfalls.
Connecting a Client
How to connect a browser or Node.js client to a Socket.IO server, configure connection options, and handle the connection lifecycle correctly.
What Is Socket.IO?
Socket.IO is a JavaScript library that enables low-latency, bidirectional, event-based communication between web clients and servers, built on top of the Engine.IO transport layer.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics