Deployment and Troubleshooting
🎯 Introduction
Once the local chat room works, remote clients need to reach the same service. During deployment, first verify that the process runs, its address is reachable, and the proxy forwards correctly, then check authentication and message handling. This article deploys a single instance first, then introduces the capabilities needed when adding instances.
🧰 Start and Verify the Service
Continue using the previous server.mjs and clients. Replace the server's original listen call with the following code to configure its port through an environment variable.
const port = Number(process.env.PORT || 3000);
httpServer.listen(port, () => {
console.log(`Server started on port: ${port}`);
});
Install Node.js and the project dependencies on the server, then start the service. Continue using Node.js 24.19.0, socket.io 4.8.1, and socket.io-client 4.8.1.
PORT=3000 node server.mjs
Change the client to read its connection address from the URL environment variable, keeping its valid credentials.
const socket = io(process.env.URL || 'http://localhost:3000', {
auth: { token: 'demo-token-a' }
});
First run the client on the same machine to verify connection and room joining. Then run the previous User B client to send a message and check reception and acknowledgement.
URL=http://localhost:3000 node client.mjs
To test from another machine, set URL to the server's domain or address and make sure the firewall allows the corresponding entry point. In deployment, keep the service running with a process manager and capture standard output.
🛠 Configure a Reverse Proxy
A reverse proxy forwards public requests to the internal Node.js service. Place this Nginx configuration inside the http block to test locally on port 8080. Public HTTPS access also requires a certificate for your domain.
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 8080;
location /socket.io/ {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_read_timeout 75s;
}
}
The Upgrade and Connection headers allow upgrading to WebSocket. Socket.IO also supports HTTP long-polling by default; both transports are forwarded through this path. The proxy read timeout should exceed the combined Socket.IO heartbeat interval and timeout, about 45 seconds with the defaults. Otherwise, the proxy may close connections periodically. Reverse proxy configuration
Start the client with URL=http://localhost:8080 and test joining and messaging again. The default Socket.IO request path is /socket.io/; the client, server, and proxy must agree on it.
Configure Cross-Origin Browser Access
This course's Node.js client can specify the server address directly. For a Vue page on a separate domain, add the actual frontend origin to the Server's CORS configuration, for example cors: { origin: 'https://chat.example.com' }. Authentication still uses auth credentials. Requests from non-browser clients also require identity validation.
🧱 Where to Start Troubleshooting
| Symptom | Check first |
|---|---|
| EADDRINUSE at startup | Whether the port is already in use |
| Persistent connect_error | Address, port, server availability, and error message |
| UNAUTHENTICATED | Whether the token is correct and matches server authentication rules |
| Connects but receives no messages | Event names, room join result, and server-side recipient scope |
| Disconnects at regular intervals | Proxy idle timeout and heartbeat configuration |
| One message prints multiple times | Application listeners repeatedly registered inside connect |
| Empty history after restart | This project stores history in process memory |
Logs can record userId, event name, room, and error reason. Avoid logging complete tokens. If saving a message fails, return a rejection or error rather than acknowledging success just because the event arrived.
🧰 Optional: Broadcast Across Two Instances
By default, rooms manage only connections in the current process. To communicate between users connected to different processes, use the Redis adapter. An adapter is the Socket.IO component that manages rooms and distributes broadcasts; this implementation uses Redis to relay broadcasts to other instances.
Using Node.js 24.19.0 and Socket.IO 4.8.1 as the baseline, install @socket.io/redis-adapter 8.3.0 and redis 4.7.0, and provide a reachable Redis 7 service.
npm install --save-exact @socket.io/redis-adapter@8.3.0 redis@4.7.0
Import these modules in server.mjs, then connect to Redis after creating io and before listen.
import { createClient } from 'redis';
import { createAdapter } from '@socket.io/redis-adapter';
const pub = createClient({ url: process.env.REDIS_URL });
const sub = pub.duplicate();
pub.on('error', (error) => console.error(error.message));
sub.on('error', (error) => console.error(error.message));
await Promise.all([pub.connect(), sub.connect()]);
io.adapter(createAdapter(pub, sub));
Start two instances with different PORT values and the same REDIS_URL. Point A's URL to port 3000 and B's to 3001. Both should join room1; B should receive messages sent by A.
This experiment verifies only cross-instance live broadcasting. Each process still has its own histories Map, so history queries are not consistent across instances. Further expansion requires moving history to a shared database. Login sessions and membership permissions should also be shared. Default long-polling requires the load balancer to route requests from the same connection to the same instance. The Redis adapter does not replace that routing configuration. Redis adapter
❓ Questions and Answers
Q1: Does a running process mean deployment succeeded?
You must also verify connection, identity, room joining, and a message round trip through the actual entry point. A running process alone does not verify proxy forwarding or application listeners.
Q2: What should happen before the service exits?
Stop accepting new application operations, wait for ongoing work to finish, then close Socket.IO and dependency connections. In production, configure an exit grace period through the process manager. Clients restore subscriptions and retrieve missed records after reconnecting.
🧪 Exercise
Run the same authentication, join, send, and leave tests through both the direct port and the proxy port. Stop the Node.js service and observe client errors, then restore it and confirm rejoining. Record one failure, where you checked, and how you fixed it.
🎉 You can now move your Socket.IO service from local execution to a deployment you can verify.
