API & Authentication

Socket.IO Setup & Deployment Guide

Event-based real-time library with rooms, acknowledgements and auto-reconnect – build a chat, then scale it with Redis and Nginx.

Updated Official documentation ↗

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 needVersion / notes
Node.jsCurrent LTS release
BasicsExpress and JavaScript events

3. Local setup

  1. 1Create the project

    Install the server and Express.

    BASH
    mkdir socketio-chat && cd socketio-chat
    npm init -y && npm pkg set type=module
    npm install express socket.io

4. Create & run a project

  1. 1Write the server

    Socket.IO attaches to the HTTP server and also serves its client script at /socket.io/socket.io.js.

    server.js
    import 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'));
  2. 2Write the client

    Served from public/; joins a room and sends messages. (In React/Vite use npm install socket.io-client and import { 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>
  3. 3Run it

    Open http://localhost:3000 in two tabs and chat.

    BASH
    node --env-file=.env server.js

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

.env
PORT=3000
CLIENT_ORIGIN=http://localhost:5173
REDIS_URL=redis://localhost:6379

Key dependencies

Package / toolUsed for
socket.ioServer
socket.io-clientClient for bundlers, React, Node
@socket.io/redis-adapter + redisBroadcast across several server instances
@socket.io/admin-ui (optional)Dashboard of connected sockets

Folder structure

project structure
socketio-chat/
├── public/index.html
├── server.js
├── .env
└── package.json

Essential commands

CommandWhat it does
node server.jsStart the server
DEBUG=socket.io* node server.jsVerbose debug logs
localStorage.debug = "socket.io-client:*"Client debug logs (browser console)

6. Production deployment

Server & hosting requirements

RequirementRecommendation
ServerNode.js LTS on a VPS/containers
ProxyNginx with WebSocket upgrade headers
Several instancesRedis adapter + sticky sessions (or WebSocket-only transport)
TLSHTTPS/WSS via Let’s Encrypt

Deployment steps

  1. 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.

    BASH
    ssh 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_IP
  2. 2Install 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.

    BASH
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
    source ~/.bashrc
    nvm install --lts
    node -v && npm -v
  3. 3Get the code and build it

    Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with npm ci and build.

    BASH
    git clone https://github.com/you/your-app.git /var/www/socketio-chat
    cd /var/www/socketio-chat
    npm ci --omit=dev
  4. 4Keep the app running with PM2

    PM2 restarts the app if it crashes and starts it again after a server reboot. pm2 startup prints one command – run it with sudo, then pm2 save.

    BASH
    sudo 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 deploy
  5. 5Install Nginx as a reverse proxy

    Nginx receives requests on ports 80/443 and forwards them to your app on 127.0.0.1:3000. Replace example.com with your domain. The Upgrade/Connection headers in this config are required for Socket.IO’s WebSocket transport.

    /etc/nginx/sites-available/example.com
    server {
        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";
        }
    }
  6. 6Enable the site and reload Nginx

    Link the config into sites-enabled, test it and reload. nginx -t must say syntax is ok before you reload.

    BASH
    sudo apt install -y nginx
    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
  7. 7Open 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.

    BASH
    sudo ufw allow OpenSSH
    sudo ufw allow 'Nginx Full'   # ports 80 and 443 (after installing Nginx)
    sudo ufw enable
    sudo ufw status
  8. 8Point your domain to the server

    In your domain registrar's DNS panel add an A record for @ (and www) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check with dig or 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.com
  9. 9Add 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.

    BASH
    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d example.com -d www.example.com
    sudo certbot renew --dry-run
  10. 10Scale 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.

    JS
    npm 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.

terminal$ node --env-file=.env server.jsSocket.IO on http://localhost:3000# browser tab 1 # browser tab 2joined general joined generalab12: hello ab12: hello cd34: hi!left cd34 transport close
Figure 1: terminal output of the sample Socket.IO project (section 4).
1Events + rooms2PM2 instances3Redis adapter4Nginx upgrade +sticky5HTTPS / WSSclients
Figure 2: production deployment flow (section 6).
socketio-chat/├── public/index.html├── server.js├── .env└── package.json
Figure 3: project folder structure (section 5).

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).