MyInternships.in

Authentication & Security

Node.js WebSockets and Socket.IO

WebSockets keep a connection open in both directions so the server can push data without the client polling. Socket.IO adds rooms, automatic reconnection and fallbacks on top.


What is WebSockets and Socket.IO in Node.js?

WebSockets keep a connection open in both directions so the server can push data without the client polling. Socket.IO adds rooms, automatic reconnection and fallbacks on top.

WebSockets and Socket.IO example

A simple chat server
JavaScript
import { Server } from 'socket.io';

const io = new Server(httpServer, { cors: { origin: process.env.CLIENT_URL } });

io.use((socket, next) => {
  try {
    socket.data.user = jwt.verify(socket.handshake.auth.token, process.env.JWT_SECRET);
    next();
  } catch {
    next(new Error('Unauthorized'));
  }
});

io.on('connection', socket => {
  socket.join(`user:${socket.data.user.sub}`);

  socket.on('message', text => {
    io.to(`room:${roomId}`).emit('message', { text, from: socket.data.user.sub });
  });

  socket.on('disconnect', () => console.log('left'));
});

Key points to remember

  • Authenticate during the handshake, not after the connection is established.
  • Rooms are how you target a user or a group instead of broadcasting to everyone.
  • Across multiple processes you need the Redis adapter, or messages reach only one worker.
  • Server-Sent Events are simpler when you only need one-way updates.

Common mistakes with WebSockets and Socket.IO

  • Clustering without the Redis adapter, so users connected to different workers cannot see each other.
  • Emitting to all clients when a room would do.

Node.js WebSockets and Socket.IO— Interview Questions & FAQs

WebSockets or Server-Sent Events?+

Server-Sent Events are simpler and enough for one-way updates such as notifications or live scores. Use WebSockets when the client also needs to send messages continuously, as in chat or collaborative editing.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships