I have a WebSocket server that functions correctly in my local environment, where it connects, sends, and receives messages without issues.
However, in my production environment, the WebSocket server logs connections and disconnections (“Nova conexão!” and “Cliente desconectado”), but it does not log any message events (“Mensagem recebida”). I have verified this by adding logging statements to each event handler.
The main difference between my local and production environments is that in production, the WebSocket server is running behind an Nginx proxy. Here is my Nginx configuration for the WebSocket:
location /websocket/ {
proxy_pass http://localhost:8888;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
}
And here is a simplified version of my WebSocket server code:
wss.on("connection", (ws: WebSocket) => {
console.log("Nova conexão!");
ws.on("message", (message: string) => {
console.log(`Mensagem recebida: ${message}`);
// Message handling logic omitted for brevity
});
ws.on("close", () => {
console.log("Cliente desconectado");
// Disconnection handling logic omitted for brevity
});
});
My WebSocket client connects to wss://myserver.com/websocket/ and sends an “online” action message upon connection. Here is a simplified version of my client code:
$(document).ready(function () {
const socket = new WebSocket("wss://myserver.com/websocket/");
socket.onopen = function () {
const userId = $("#userId").text();
socket.send(JSON.stringify({ action: "online", data: { user_id: userId } }));
};
socket.onmessage = function (event) {
const data = JSON.parse(event.data);
// Message handling logic omitted for brevity
};
});
In production, the WebSocket server correctly logs connections and disconnections, but it does not log any incoming messages. How can I troubleshoot or configure Nginx to ensure that WebSocket messages are properly received and logged by my server?