API & Authentication

WebSockets Setup & Deployment Guide

Real-time, two-way communication over one connection – build a WebSocket server with ws, a browser client, and proxy it with Nginx (wss).

Updated Official documentation ↗

1. Introduction & use cases

WebSocket is a protocol that keeps a single TCP connection open between browser and server, so both sides can send messages at any time with very little overhead. A connection starts as an HTTP request with an Upgrade: websocket header and then switches protocols.

Use ws:// locally and wss:// (WebSocket over TLS) in production. Browsers have the WebSocket API built in; on Node.js the ws package is the standard, minimal server. For automatic reconnection, rooms and fallbacks, see Socket.IO.

Where it is used

  • Chat and collaborative editing
  • Live dashboards, prices and sports scores
  • Multiplayer games
  • Notifications and IoT device control

2. Prerequisites

You needVersion / notes
Node.jsCurrent LTS release
BrowserAny modern browser (DevTools → Network → WS shows frames)

3. Local setup

  1. 1Create the project

    Install ws.

    BASH
    mkdir ws-chat && cd ws-chat
    npm init -y && npm pkg set type=module
    npm install ws

4. Create & run a project

  1. 1Write the server

    Broadcast every message to all connected clients and detect dead connections with ping/pong heartbeats.

    server.js
    import { WebSocketServer, WebSocket } from 'ws';
    
    const wss = new WebSocketServer({ port: Number(process.env.PORT) || 8080 });
    
    wss.on('connection', (ws, req) => {
      ws.isAlive = true;
      ws.on('pong', () => { ws.isAlive = true; });
      ws.send(JSON.stringify({ type: 'welcome', text: 'Connected!' }));
    
      ws.on('message', (data) => {
        const text = data.toString().slice(0, 500);
        for (const client of wss.clients) {
          if (client.readyState === WebSocket.OPEN) client.send(JSON.stringify({ type: 'chat', text }));
        }
      });
    });
    
    // heartbeat: close connections that stopped answering
    setInterval(() => {
      for (const ws of wss.clients) {
        if (!ws.isAlive) { ws.terminate(); continue; }
        ws.isAlive = false;
        ws.ping();
      }
    }, 30000);
    
    console.log('WebSocket server on ws://localhost:8080');
  2. 2Write a browser client

    Save as index.html and open it in two tabs; messages appear in both.

    index.html
    <!doctype html>
    <input id="msg" placeholder="Type and press Enter"><ul id="log"></ul>
    <script>
      const ws = new WebSocket('ws://localhost:8080');
      const list = document.getElementById('log');
      const log = (t) => { const li = document.createElement('li'); li.textContent = t; list.append(li); }; // textContent: no XSS
      ws.onmessage = (e) => { const m = JSON.parse(e.data); log(m.text); };
      ws.onclose = () => log('disconnected');
      document.getElementById('msg').onkeydown = (e) => {
        if (e.key === 'Enter') { ws.send(e.target.value); e.target.value = ''; }
      };
    </script>
  3. 3Run it

    Start the server, then open the HTML file (or serve it with any static server).

    BASH
    node server.js
    # test from the terminal without a browser:
    npx wscat -c ws://localhost:8080

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

5. Development configuration

Environment variables

.env
PORT=8080
ALLOWED_ORIGINS=http://localhost:5173,https://example.com

Key dependencies

Package / toolUsed for
wsFast, minimal WebSocket server/client for Node.js
wscatCommand-line WebSocket client for testing
Redis pub/subShare messages between several server instances
Socket.IO (alternative)Rooms, reconnection, acknowledgements

Folder structure

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

Essential commands

CommandWhat it does
node server.jsStart the server
npx wscat -c ws://localhost:8080Connect from the terminal
DevTools → Network → WSInspect frames in the browser

6. Production deployment

Server & hosting requirements

RequirementRecommendation
ServerNode.js LTS; connections are long-lived, so plan RAM per connection
ProxyNginx with Upgrade/Connection headers and long timeouts
TLSwss:// – browsers block ws:// from HTTPS pages
ScalingSticky sessions or a pub/sub layer (Redis) for multiple instances

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/ws-chat
    cd /var/www/ws-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 ws-chat
    pm2 startup          # run the command it prints
    pm2 save
    pm2 logs ws-chat        # live logs
    pm2 restart ws-chat     # after each deploy
  5. 5Nginx: proxy the upgrade

    The Upgrade and Connection headers switch the protocol; raise the read timeout so idle sockets are not cut after 60 s.

    /etc/nginx/sites-available/ws.example.com
    server {
        listen 80;
        server_name ws.example.com;
    
        location / {
            proxy_pass http://127.0.0.1:8080;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;
            proxy_read_timeout 3600s;
            proxy_send_timeout 3600s;
        }
    }
  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. 10Connect with wss:// from the site

    After SSL, clients must use the secure URL.

    JS
    const ws = new WebSocket('wss://ws.example.com');

🗺 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 server.jsWebSocket server on ws://localhost:8080$ npx wscat -c ws://localhost:8080Connected (press CTRL+C to quit)< {"type":"welcome","text":"Connected!"}> hello< {"type":"chat","text":"hello"}
Figure 1: terminal output of the sample WebSockets project (section 4).
1ws server :80802PM23Nginx Upgradeheaders4TLS → wss://5Browsers connected
Figure 2: production deployment flow (section 6).
ws-chat/├── server.js├── public/index.html└── package.json
Figure 3: project folder structure (section 5).

8. Common errors & solutions

WebSocket connection failed with 400/426 behind Nginx

The proxy is not forwarding Upgrade/Connection headers or uses HTTP/1.0. Add the headers and proxy_http_version 1.1.

Mixed content: insecure WebSocket connection may not be initiated from a page loaded over HTTPS

Use wss:// when the page is served over HTTPS.

Connections drop after about 60 seconds of silence

Proxy/load-balancer idle timeout. Raise proxy_read_timeout and send heartbeats (ping/pong).

Messages reach only some users when running 2+ processes

Each process knows only its own sockets. Publish messages through Redis pub/sub (or use Socket.IO with the Redis adapter).

Memory grows over time

Dead connections are never closed. Use the heartbeat pattern and remove listeners on close.

Best practices

  • Authenticate during the handshake (token in a cookie or the first message) and check Origin.
  • Validate and size-limit every message.
  • Implement reconnection with back-off on the client.
  • Use heartbeats to clean up dead connections.
  • Use wss:// only in production.