1. Introduction & use cases
Socket.IO is a library for real-time, bidirectional, event-based communication. It usually runs over WebSockets but adds features you would otherwise build yourself: automatic reconnection, rooms and namespaces, acknowledgements (callbacks), broadcasting, and an HTTP long-polling fallback.
It has its own protocol, so a Socket.IO client must talk to a Socket.IO server (not a plain WebSocket server). Servers exist for Node.js and other languages; clients for browsers, React Native, Java, Swift and more.
Where it is used
- Chat apps with rooms and typing indicators
- Live notifications and activity feeds
- Collaborative tools and multiplayer games
- Real-time dashboards and order tracking
2. Prerequisites
| You need | Version / notes |
|---|---|
| Node.js | Current LTS release |
| Basics | Express and JavaScript events |
3. Local setup
1Create the project
Install the server and Express.
BASHmkdir socketio-chat && cd socketio-chat npm init -y && npm pkg set type=module npm install express socket.io
4. Create & run a project
1Write the server
Socket.IO attaches to the HTTP server and also serves its client script at
/socket.io/socket.io.js.server.jsimport express from 'express'; import { createServer } from 'node:http'; import { Server } from 'socket.io'; const app = express(); const httpServer = createServer(app); const io = new Server(httpServer, { cors: { origin: process.env.CLIENT_ORIGIN?.split(',') ?? 'http://localhost:5173' }, }); app.use(express.static('public')); io.on('connection', (socket) => { socket.on('join', (room, ack) => { socket.join(room); socket.to(room).emit('system', `${socket.id} joined ${room}`); ack?.({ ok: true, room }); }); socket.on('chat', ({ room, text }) => { io.to(room).emit('chat', { from: socket.id, text: String(text).slice(0, 500) }); }); socket.on('disconnect', (reason) => console.log('left', socket.id, reason)); }); httpServer.listen(Number(process.env.PORT) || 3000, () => console.log('Socket.IO on http://localhost:3000'));2Write the client
Served from
public/; joins a room and sends messages. (In React/Vite usenpm install socket.io-clientandimport { io } from 'socket.io-client'.)public/index.html<!doctype html> <input id="t" placeholder="Message"><ul id="log"></ul> <script src="/socket.io/socket.io.js"></script> <script> const socket = io(); const add = (s) => { const li = document.createElement('li'); li.textContent = s; document.getElementById('log').append(li); }; // textContent: no XSS socket.emit('join', 'general', (res) => add(`joined ${res.room}`)); socket.on('chat', (m) => add(`${m.from.slice(0, 4)}: ${m.text}`)); socket.on('system', add); document.getElementById('t').onkeydown = (e) => { if (e.key === 'Enter') { socket.emit('chat', { room: 'general', text: e.target.value }); e.target.value = ''; } }; </script>3Run it
Open http://localhost:3000 in two tabs and chat.
BASHnode --env-file=.env server.js
✅ When it works you should see output like Figure 1.
5. Development configuration
Environment variables
PORT=3000
CLIENT_ORIGIN=http://localhost:5173
REDIS_URL=redis://localhost:6379Key dependencies
| Package / tool | Used for |
|---|---|
socket.io | Server |
socket.io-client | Client for bundlers, React, Node |
@socket.io/redis-adapter + redis | Broadcast across several server instances |
@socket.io/admin-ui (optional) | Dashboard of connected sockets |
Folder structure
socketio-chat/
├── public/index.html
├── server.js
├── .env
└── package.jsonEssential commands
| Command | What it does |
|---|---|
node server.js | Start the server |
DEBUG=socket.io* node server.js | Verbose debug logs |
localStorage.debug = "socket.io-client:*" | Client debug logs (browser console) |
6. Production deployment
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| Server | Node.js LTS on a VPS/containers |
| Proxy | Nginx with WebSocket upgrade headers |
| Several instances | Redis adapter + sticky sessions (or WebSocket-only transport) |
| TLS | HTTPS/WSS via Let’s Encrypt |
Deployment steps
1Prepare an Ubuntu server
Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.
BASHssh root@YOUR_SERVER_IP apt update && apt upgrade -y adduser deploy usermod -aG sudo deploy # copy your SSH key to the new user, then log in as deploy rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy exit ssh deploy@YOUR_SERVER_IP2Install Node.js on the server
Install the current LTS release with nvm (or the NodeSource packages). Use the same major version as on your computer.
BASHcurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash source ~/.bashrc nvm install --lts node -v && npm -v3Get the code and build it
Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with
npm ciand build.BASHgit clone https://github.com/you/your-app.git /var/www/socketio-chat cd /var/www/socketio-chat npm ci --omit=dev4Keep the app running with PM2
PM2 restarts the app if it crashes and starts it again after a server reboot.
pm2 startupprints one command – run it with sudo, thenpm2 save.BASHsudo npm install -g pm2 pm2 start server.js --name socketio-chat --node-args="--env-file=.env" pm2 startup # run the command it prints pm2 save pm2 logs socketio-chat # live logs pm2 restart socketio-chat # after each deploy5Install Nginx as a reverse proxy
Nginx receives requests on ports 80/443 and forwards them to your app on
127.0.0.1:3000. Replaceexample.comwith your domain. TheUpgrade/Connectionheaders in this config are required for Socket.IO’s WebSocket transport./etc/nginx/sites-available/example.comserver { listen 80; server_name example.com www.example.com; location / { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } }6Enable the site and reload Nginx
Link the config into
sites-enabled, test it and reload.nginx -tmust say syntax is ok before you reload.BASHsudo apt install -y nginx sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx7Open only the ports you need
Allow SSH, HTTP and HTTPS through the firewall. Application ports (3000, 8000 …) stay closed to the internet – Nginx forwards traffic to them.
BASHsudo ufw allow OpenSSH sudo ufw allow 'Nginx Full' # ports 80 and 443 (after installing Nginx) sudo ufw enable sudo ufw status8Point your domain to the server
In your domain registrar's DNS panel add an A record for
@(andwww) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check withdigor an online DNS checker.OUTPUT# Type Name Value TTL # A @ 203.0.113.10 3600 # A www 203.0.113.10 3600 dig +short example.com9Add free HTTPS with Let’s Encrypt
Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with
--dry-run.BASHsudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com sudo certbot renew --dry-run10Scale to several instances with Redis
The Redis adapter forwards
io.emit/room broadcasts to all instances. With HTTP long-polling enabled, the load balancer must also use sticky sessions; alternatively force the WebSocket transport on clients.JSnpm install @socket.io/redis-adapter redis import { createAdapter } from '@socket.io/redis-adapter'; import { createClient } from 'redis'; const pub = createClient({ url: process.env.REDIS_URL }); const sub = pub.duplicate(); await Promise.all([pub.connect(), sub.connect()]); io.adapter(createAdapter(pub, sub)); // client without polling (no sticky sessions needed): // const socket = io('https://example.com', { transports: ['websocket'] });
🗺 The whole path from your code to the live site is drawn in the deployment diagram.
7. Images & screenshots
Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.
8. Common errors & solutions
CORS error / xhr poll error
Set cors: { origin: [...] } on the server with your exact front-end origin.
Session ID unknown with several instances
Long-polling requests hit different processes. Enable sticky sessions or use transports: ['websocket'].
Client connects, then reconnects every ~25 s
A proxy closes idle connections or strips upgrade headers. Add the WebSocket headers and raise proxy_read_timeout.
io.emit reaches only some users
Multiple processes without an adapter. Add the Redis adapter.
Version mismatch: client cannot connect
Client and server major versions must be compatible (v4 client ↔ v4 server).
Best practices
- Authenticate in a connection middleware (
io.use) with a token. - Validate payloads and rate-limit events.
- Use rooms instead of looping over sockets.
- Use acknowledgements for actions that must succeed.
- Plan for horizontal scale early (Redis adapter).