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 need | Version / notes |
|---|---|
| Node.js | Current LTS release |
| Browser | Any modern browser (DevTools → Network → WS shows frames) |
3. Local setup
1Create the project
Install
ws.BASHmkdir ws-chat && cd ws-chat npm init -y && npm pkg set type=module npm install ws
4. Create & run a project
1Write the server
Broadcast every message to all connected clients and detect dead connections with ping/pong heartbeats.
server.jsimport { 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');2Write a browser client
Save as
index.htmland 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>3Run it
Start the server, then open the HTML file (or serve it with any static server).
BASHnode 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
PORT=8080
ALLOWED_ORIGINS=http://localhost:5173,https://example.comKey dependencies
| Package / tool | Used for |
|---|---|
ws | Fast, minimal WebSocket server/client for Node.js |
wscat | Command-line WebSocket client for testing |
Redis pub/sub | Share messages between several server instances |
Socket.IO (alternative) | Rooms, reconnection, acknowledgements |
Folder structure
ws-chat/
├── server.js
├── public/index.html
└── package.jsonEssential commands
| Command | What it does |
|---|---|
node server.js | Start the server |
npx wscat -c ws://localhost:8080 | Connect from the terminal |
DevTools → Network → WS | Inspect frames in the browser |
6. Production deployment
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| Server | Node.js LTS; connections are long-lived, so plan RAM per connection |
| Proxy | Nginx with Upgrade/Connection headers and long timeouts |
| TLS | wss:// – browsers block ws:// from HTTPS pages |
| Scaling | Sticky sessions or a pub/sub layer (Redis) for multiple instances |
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/ws-chat cd /var/www/ws-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 ws-chat pm2 startup # run the command it prints pm2 save pm2 logs ws-chat # live logs pm2 restart ws-chat # after each deploy5Nginx: proxy the upgrade
The
UpgradeandConnectionheaders switch the protocol; raise the read timeout so idle sockets are not cut after 60 s./etc/nginx/sites-available/ws.example.comserver { 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; } }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-run10Connect with wss:// from the site
After SSL, clients must use the secure URL.
JSconst 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.
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.